Created
May 14, 2014 01:53
-
-
Save quatrix/e9ff52e5a2a847e8d19e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
def print_board(board): | |
for row in board: | |
for column in row: | |
print(column), | |
print("") | |
print("- " * len(board[0])) | |
def count_neighbours(x, y, board): | |
count = 0 | |
for _y in (y-1, y, y+1): | |
for _x in (x-1, x, x+1): | |
if _y == y and _x == x: | |
continue | |
if _y < 0 or _x < 0: | |
continue | |
if _y >= len(board) or _x >= len(board[0]): | |
continue | |
count += board[_y][_x] | |
return count | |
def gol(x, y, board): | |
""" | |
1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. | |
2. Any live cell with two or three live neighbours lives on to the next generation. | |
3. Any live cell with more than three live neighbours dies, as if by overcrowding. | |
4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. | |
""" | |
neighbours = count_neighbours(x, y, board) | |
if board[y][x]: | |
if neighbours < 2: | |
return 0 | |
elif neighbours <= 3: | |
return 1 | |
else: | |
return 0 | |
else: | |
if neighbours == 3: | |
return 1 | |
return 0 | |
def next_step(board): | |
return [[gol(x,y, board) for x in xrange(len(board[0])) ] for y in xrange(len(board))] | |
def main(): | |
board = [ | |
[0,0,0,0,0,0], | |
[0,0,1,0,0,0], | |
[1,0,1,0,0,0], | |
[0,1,1,0,0,0], | |
[0,0,0,0,0,0], | |
[0,0,0,0,0,0], | |
] | |
while True: | |
print_board(board) | |
new_board = next_step(board) | |
if new_board == board: | |
break | |
board = new_board | |
time.sleep(0.1) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment