/
life.py
129 lines (116 loc) · 4.08 KB
/
life.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import random
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.axis('off')
class GameOfLife:
"""
Conway's Game of Life.
Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population..
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
Representations => 0 : dead, 1 : alive, 2 : dying, 3 : spawing
"""
def __init__(self,board=None,size=None,iterations=None):
if board is None:
board = self.generate_board(size)
if iterations is None:
iterations = 100
self.iterations = iterations
self.board = board
self.cmap = mpl.colors.ListedColormap(['#290000','#CC0000','#800000','#E68A00'])
self.update_rules = {0:0,1:1,2:0,3:1}
try:
self.plot_board(0)
self.play_game()
except:
print('invalid board')
def generate_board(self,size=None):
"""
Generate a random game board of the requested size
"""
if size is None:
size = 100
board = []
while len(board) < size:
row = []
while len(row) < size:
boo = random.randint(0, 1)
row.append(boo)
board.append(row)
return board
def play_game(self):
"""
Play the game for as many iterations as requested
"""
i = 1
# check back here later...
while i <= (self.iterations * 2 - 1):
self.start_update()
self.plot_board(i)
i += 1
self.finish_update()
self.plot_board(i)
i += 1
def plot_board(self,iteration):
"""
Output a plot of the board to an image file according to the iteration
"""
img = plt.imshow(self.board,interpolation='nearest',cmap = self.cmap)
fig = plt.figure(1)
fig.savefig("output/t" + str(iteration) + ".png")
def start_update(self):
"""
Update the game board in-place to show spawning and dying cells
"""
self.num_rows = len(self.board)
self.num_cols = len(self.board[0])
for i,row in enumerate(self.board):
i_opts = self.get_opts(i,self.num_rows)
for j,col in enumerate(row):
j_opts = self.get_opts(j,self.num_cols)
pos = [i,j]
nbs = self.get_neighbors(i_opts,j_opts,pos)
self.update_tile_value(nbs,i,j)
def finish_update(self):
"""
Update the game board in-place to show only living and non-living cells
"""
for i in range(self.num_rows):
for j in range(self.num_cols):
self.board[i][j] = self.update_rules[self.board[i][j]]
def update_tile_value(self,neighbors,i,j):
"""
Replace all spawning / dying cells with living / non-living cells
"""
if self.board[i][j] == 0:
if neighbors == 3:
self.board[i][j] = 3
else:
if neighbors not in [2,3]:
self.board[i][j] = 2
def get_opts(self,pos,lim):
"""
Get all possible options surrounding a cell along one dimension
"""
opts = [pos]
if pos < lim - 1:
opts.append(pos + 1)
if pos > 0:
opts.append(pos - 1)
return opts
def get_neighbors(self,row_opts,col_opts,pos):
"""
Count the number of living cells surrounding a cell
"""
neighbors = 0
for e in row_opts:
for f in col_opts:
if [e,f] != pos:
tile = self.board[e][f]
if tile in [1,2]:
neighbors += 1
return neighbors
sample_board = [[0,1,0,1],[1,0,0,1],[1,0,1,0],[1,0,0,1]]
sample_board = [[0,1,0,1,0],[1,0,0,1,1],[1,0,1,0,0],[1,0,0,1,1],[0,1,0,1,0]]
GameOfLife()