Advertisement
retrocombine

conway

Sep 29th, 2013
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. __author__ = 'rebecca'
  2.  
  3. # Literal version of the game of life.
  4.  
  5. import itertools as it
  6.  
  7.  
  8. def next_round(the_world, updated_world):
  9.     the_world.update(updated_world)
  10.  
  11.  
  12. def togglecell(x, y):
  13.  
  14.     if the_world[x, y] == False:
  15.         the_world[x, y] = True
  16.     else:
  17.         the_world[x, y] = False
  18.  
  19.  
  20. def neighbors(x, y):
  21.  
  22.     neighbors = []
  23.     for i, j in it.product(range(x - 1, x + 2), range(y - 1, y + 2)):
  24.         if i >= 0 & i <= (wide - 1):
  25.             if j >= 0 & j <= (high - 1):
  26.                 if (i, j) != (x, y):
  27.                     try:
  28.                         neighbors.append(the_world[(i,j)])
  29.                     except KeyError:
  30.                         pass # if the_world[(i, j)] does not exist, skip it.
  31.     return neighbors
  32.  
  33.  
  34. def checkneighbors(x, y):
  35.  
  36.     live_neighbors = neighbors(x, y).count(True)
  37.  
  38.     if live_neighbors < 2:
  39.         updated_world.update({(x, y): False})
  40.     elif live_neighbors > 3:
  41.         updated_world.update({(x, y): False})
  42.     elif live_neighbors == 2:
  43.         updated_world.update({(x, y): True})
  44.     elif live_neighbors == 3:
  45.         updated_world.update({(x, y): True})
  46.     else:
  47.         print "Something went wrong!"
  48.  
  49. # Initialize.
  50. wide = int(raw_input("How wide?\n>"))
  51. high = int(raw_input("How high?\n>"))
  52.  
  53. the_world = {}
  54. updated_world = {}
  55.  
  56. for i, j in it.product(range(wide), range(high)):
  57.     the_world.update({(i,j): False})
  58.  
  59. for i, j in it.product(range(wide), range(high)):
  60.     checkneighbors(i, j)
  61.  
  62. print the_world
  63.  
  64. next_round(the_world, updated_world)
  65.  
  66. print the_world
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement