Skip to content

Instantly share code, notes, and snippets.

@lvidarte
Last active June 9, 2017 06:24
Show Gist options
  • Save lvidarte/01fc3b017ae91f2983bcc65985cf57b7 to your computer and use it in GitHub Desktop.
Save lvidarte/01fc3b017ae91f2983bcc65985cf57b7 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
"""
Author: Leo Vidarte <http://nerdlabs.com.ar>
This is free software,
you can redistribute it and/or modify it
under the terms of the GPL version 3
as published by the Free Software Foundation.
"""
"""
Las transiciones dependen del número de células vecinas vivas:
* Una célula muerta con exactamente 3 células vecinas vivas "nace"
(al turno siguiente estará viva).
* Una célula viva con 2 ó 3 células vecinas vivas sigue viva.
* En otro caso muere o permanece muerta (por "soledad" o "superpoblación").
"""
DEAD = 0
ALIVE = 1
def print_board(board):
for row in board:
print(' '.join(['.' if col == DEAD else '#' for col in row]))
def get_board_size(board):
width = len(board[0]) # explícito mejor que implícito
height = len(board)
return (width, height)
def count_neighbors_alive(cell_pos, board):
x_center, y_center = cell_pos
width, height = get_board_size(board)
x_left = x_center-1 if x_center-1 >= 0 else width-1
x_right = x_center+1 if x_center+1 < width else 0
y_up = y_center-1 if y_center-1 >= 0 else height-1
y_down = y_center+1 if y_center+1 < height else 0
return (board[y_up][x_left],
board[y_up][x_center],
board[y_up][x_right],
board[y_center][x_left],
board[y_center][x_right],
board[y_down][x_left],
board[y_down][x_center],
board[y_down][x_right]).count(ALIVE)
def get_next_cell_state(cell_state, neighbors_alive):
if (cell_state == DEAD and neighbors_alive == 3) or \
(cell_state == ALIVE and neighbors_alive in (2, 3)):
return ALIVE
else:
return DEAD
if __name__ == '__main__':
# Glider
board = [
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
]
print_board(board)
width, height = get_board_size(board)
for x in range(width):
for y in range(height):
cell_pos = (x, y)
cell_state = board[y][x] # alive or dead
neighbors_alive = count_neighbors_alive(cell_pos, board)
cell_next_state = get_next_cell_state(cell_state, neighbors_alive)
print(cell_pos, neighbors_alive, cell_state, cell_next_state)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment