-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgameoflife.py
55 lines (41 loc) · 1.34 KB
/
gameoflife.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Program for playing the game of Life.
from life import LifeGrid
# Define the initial configuration of live cells.
INIT_CONFIG = [ (1, 2), (2, 1), (2, 2), (2, 3) ]
# Set the size of the grid.
GRID_WIDTH = 5
GRID_HEIGHT = 5
# Indicate the number of generations.
NUM_GENS = 8
def main():
# Construct the game grid and confiture it.
grid = LifeGrid( GRID_WIDTH, GRID_HEIGHT)
grid.configure( INIT_CONFIG )
# Play the game.
draw( grid )
for i in range( NUM_GENS ):
evolve( grid )
draw( grid )
# Generates the next generation of organisms.
def evolve( grid ):
# List for storing the live cells of the next generation.
liveCells = list()
# Iterate over the elements of the grid.
for i in range( grid.numRows() ):
for j in range( grid.numCols() ):
#print '( ' + str(i) + ', ' + str(j) + ' )',
# Determine the number of live neighbors for this cell.
neighbors = grid.numLiveNeighbors( i, j )
#print neighbors
# Add the (i, j) tuple to liveCells if this cell contains
# a live organisms in the next generation.
if (neighbors == 2 and grid.isLiveCell(i, j)) or (neighbors == 3):
liveCells.append( (i, j) )
# Reconfigure the grid using the liveCells coord list.
grid.configure( liveCells )
# Prints a text-based representation of the game grid.
def draw( grid ):
grid.print_config()
print ""
# Executes the main routine
main()