Skip to content

Instantly share code, notes, and snippets.

@lvidarte
Last active June 9, 2017 06:24
Show Gist options
  • Save lvidarte/c83def41bd8af23090a6d2ff5e9679cc to your computer and use it in GitHub Desktop.
Save lvidarte/c83def41bd8af23090a6d2ff5e9679cc 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
def tick(board):
width, height = get_board_size(board)
board_ = [[DEAD] * width for _ in range(height)]
for x in range(width):
for y in range(height):
cell_pos = (x, y)
cell_status = board[y][x]
neighbords_alive = count_neighbors_alive(cell_pos, board)
board_[y][x] = get_next_cell_state(cell_status, neighbords_alive)
return board_
if __name__ == '__main__':
from time import sleep
# 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],
]
for i in range(33):
width, _ = get_board_size(board)
if i:
print('-' * ((width * 2) - 1))
print_board(board)
board = tick(board)
sleep(.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment