Skip to content

Instantly share code, notes, and snippets.

@lvidarte
Last active June 9, 2017 06:23
Show Gist options
  • Save lvidarte/c1d014121eca607ad7918e14a51a0c15 to your computer and use it in GitHub Desktop.
Save lvidarte/c1d014121eca607ad7918e14a51a0c15 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)
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)
neighbors_alive = count_neighbors_alive(cell_pos, board)
print(cell_pos, neighbors_alive)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment