Skip to content

Instantly share code, notes, and snippets.

@1328
Created January 8, 2016 14:59
Show Gist options
  • Select an option

  • Save 1328/b271573caaea5e3df9d2 to your computer and use it in GitHub Desktop.

Select an option

Save 1328/b271573caaea5e3df9d2 to your computer and use it in GitHub Desktop.
Game of Life
import random
import os
import time
from pprint import pprint
def populate_board(x_size = 40, y_size = 40, density = .3):
''' build a board x X y size '''
board =set()
population = x_size * y_size * density
# note: at higher densities there are better ways to do this that will not
# involve trying to add the same coordinate to the set again and again
while len(board)< population:
x = random.randrange(x_size)
y = random.randrange(y_size)
board.add((x,y))
return board
def find_neighbors(x,y, BH, BW):
''' return a set containing neighbors to x,y '''
# stole your code here
neighbor_cells = [(x, (y + 1) %BW),(x, (y - 1) %BW),((x + 1) %BH, y),
((x - 1) %BH, y),((x + 1) %BH, (y + 1) %BW),
((x - 1) %BH, (y - 1) %BW),((x + 1) %BH, (y - 1) %BW),
((x - 1) %BH, (y + 1) %BW)]
return set(neighbor_cells)
def live_or_die(board, x_size = 40, y_size = 40):
''' generates a new board based on GOL rules
note:
by using sets we can avoid iterating over the entire board and instead
just need to check each living cell and all of its neighbors to see if
they fit into the rules to remain alive
'''
new_board = set()
all_neighbors = set()
# now look how fun sets are:
for x,y in board:
neighbors = find_neighbors(x, y, x_size, y_size)
neighbor_count = len(neighbors & board)
if neighbor_count == 2 or neighbor_count == 3:
new_board.add((x,y))
# keep a running tab of all neighboring cells
all_neighbors |= neighbors
# note: we have tracked a list of each cell boarding another living cell so
# that we can see if any of these neighboring cells has just 3 neighbors and
# so can become alive again
# but first we remove all the cells from all_neighbors that were originally
# alive
all_neighbors -= board
# now all_neighbors contains any dead cell that is adjacent to at least one
# living cell
for x,y in all_neighbors:
neighbors = find_neighbors(x, y, x_size, y_size)
neighbor_count = len(neighbors & board)
if neighbor_count == 3:
new_board.add((x,y))
return new_board
def print_board(board, x_size = 40, y_size = 40):
# here is the only time we have to run through the entire x X y range
for y in range(y_size):
line = ''.join('X' if (x,y) in board else '.' for x in range(x_size))
print(line)
def play():
X_SIZE = 70
Y_SIZE = 70
board = populate_board(X_SIZE,Y_SIZE)
quit = False
while True:
os.system('cls')
print_board(board, X_SIZE, Y_SIZE)
if quit:
break
board = live_or_die(board, X_SIZE, Y_SIZE)
time.sleep(.05)
if len(board) == 0:
quit = True
# probably should get used to using if __name, etc., like:
if __name__ == '__main__':
play()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment