-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGameOfLife.py
189 lines (161 loc) · 6.81 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
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
##
## MIT License
##
## Copyright (c) 2017 Luca Angioloni
##
## Permission is hereby granted, free of charge, to any person obtaining a copy
## of this software and associated documentation files (the "Software"), to deal
## in the Software without restriction, including without limitation the rights
## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
## copies of the Software, and to permit persons to whom the Software is
## furnished to do so, subject to the following conditions:
##
## The above copyright notice and this permission notice shall be included in all
## copies or substantial portions of the Software.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
## SOFTWARE.
##
import os
import numpy as np
from PIL import Image
from scipy import ndimage
PIXEL_MAX = 255 # Constant representing the value of alive cells pixels (matrix elements)
DECAY = 0.9 # Constant representing the decay rate of past states when calculating the heat map
class GameOfLife:
"""
This class contains the game state and the rules of the game. (The Model)
It provides methods to get, set, modify and evolve the state following the rules.
It also provides methods to load and save the state from and to file.
Attributes:
mat current state of the game
heatmap weighted average of past states (history of past states)
do_heatmap boolean value defining what to return in get_state (the state or the heatmap)
x, y current board dimensions
initial_state backed up initial state that becomes the state when/if reset
"""
def __init__(self, x=100, y=150, mode='empty'):
"""
Init method.
Args:
x, y default dimensions of the game board
mode default initial game mode: empty or random
"""
self.reinitialize(mode, x, y)
self.do_heatmap = False
def set_do_heatmap(self, b):
"""Setter for the boolean attribute do_heatmap"""
self.do_heatmap = b
def reinitialize(self, mode='empty', x=100, y=150):
"""
This method initializes the class attributes to the default values
Args:
x, y default dimensions of the game board
mode default initial game mode: empty or random
"""
self.mode = mode
self.x = x
self.y = y
self.mat = np.zeros((self.x, self.y), dtype=np.uint8)
if self.mode == 'random': # redo it better
rand_m = np.random.randn(self.x, self.y) - 0.5 # less white cells than black voids
indexes_p = rand_m > 0
self.mat[indexes_p] = PIXEL_MAX
self.initial_state = np.copy(self.mat)
self.heatmap = np.copy(self.mat)
def reset(self):
"""Resets the state of the game to the backed up initial_state"""
self.mat = np.copy(self.initial_state)
self.heatmap = np.copy(self.mat)
def next(self):
"""
This method is the engine of the game. Calculates and updates the next state of the game following the rules.
It also updates the heatmap state.
"""
res = ndimage.uniform_filter(self.mat, size=3, mode='constant', cval=0)
res[self.mat > 128] = res[self.mat > 128] - int((1 / 9) * PIXEL_MAX)
self.mat[res <= int((1 / 9) * PIXEL_MAX)] = 0
self.mat[res >= int((4 / 9) * PIXEL_MAX)] = 0
self.mat[res == int((3 / 9) * PIXEL_MAX)] = PIXEL_MAX
self.heatmap = np.array(self.heatmap * DECAY, dtype=np.uint8)
self.heatmap[self.mat > 128] = PIXEL_MAX
def get_state(self):
"""Getter for the current state which can be the state matrix ot the heatmap matrix depending on do_heatmap"""
if self.do_heatmap:
return self.heatmap
else:
return self.mat
def set_active_cell(self, i, j):
"""Sets the cell at position (i, j) to be active(alive)"""
self.mat[i, j] = PIXEL_MAX
self.heatmap[i, j] = PIXEL_MAX
def set_inactive_cell(self, i, j):
"""Sets the cell at position (i, j) to be inactive(dead)"""
self.mat[i, j] = 0
self.heatmap[i, j] = 0
def load(self, file_name):
"""
Loads the state from file.
Args:
file_name name of the file. It can be a TXT (with known format) or PNG file
Returns:
bool True for success (file existing and correct format), False otherwise.
"""
extension = os.path.splitext(file_name)[1][1:]
if extension == "png":
im_frame = Image.open(file_name).convert('L')
width, height = im_frame.size
self.x = height
self.y = width
np_frame = np.array(im_frame.getdata())
np_frame = np.reshape(np_frame, (-1, width))
self.mat = np.zeros(np_frame.shape, dtype=np.uint8)
self.mat[np_frame > 128] = PIXEL_MAX
self.initial_state = np.copy(self.mat)
self.heatmap = np.copy(self.mat)
return True
elif extension == "txt":
rows = 0
cols = 0
with open(file_name) as f:
for i, l in enumerate(f):
if l[0] != "#":
rows += 1
if len(l) > cols:
cols = len(l)
self.mat = np.zeros((rows, cols), dtype=np.uint8)
hash_rows = 0
with open(file_name) as f:
for j, line in enumerate(f):
for k, c in enumerate(line):
if c == "#" and k is 0:
hash_rows += 1
break
elif c != "." and c != "\n":
self.mat[j-hash_rows, k] = PIXEL_MAX
self.x = rows
self.y = cols
self.initial_state = np.copy(self.mat)
self.heatmap = np.copy(self.mat)
return True
else:
print('Wrong file type')
return False
def save(self, file_name):
"""
Saves the state to a PNG file.
Args:
file_name name of the file to be saved as PNG (1 channel)
"""
extension = os.path.splitext(file_name)[1][1:]
if extension == "png":
path = file_name
else:
path = file_name + ".png"
im = Image.fromarray(self.mat)
im.save(path)