-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGame_Of_Life.py
256 lines (222 loc) · 8.52 KB
/
Game_Of_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
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
from tkinter import *
from tkinter import filedialog
import time
import json
#Grid code from Arthur Vaisse @ Stack Overflow
class Cell():
FILLED_COLOR_BG = "black"
EMPTY_COLOR_BG = "white"
FILLED_COLOR_BORDER = "black"
EMPTY_COLOR_BORDER = "black"
def __init__(self, master, x, y, size):
""" Constructor of the object called by Cell(...) """
self.master = master
self.abs = x
self.ord = y
self.size= size
self.fill= False
def _switch(self):
""" Switch if the cell is filled or not. """
self.fill= not self.fill
def draw(self):
""" order to the cell to draw its representation on the canvas """
if self.master != None :
fill = Cell.FILLED_COLOR_BG
outline = Cell.FILLED_COLOR_BORDER
if not self.fill:
fill = Cell.EMPTY_COLOR_BG
outline = Cell.EMPTY_COLOR_BORDER
xmin = self.abs * self.size
xmax = xmin + self.size
ymin = self.ord * self.size
ymax = ymin + self.size
self.master.create_rectangle(xmin, ymin, xmax, ymax, fill = fill, outline = outline)
class CellGrid(Canvas):
def __init__(self,master, rowNumber, columnNumber, cellSize, *args, **kwargs):
Canvas.__init__(self, master, width = cellSize * columnNumber , height = cellSize * rowNumber, *args, **kwargs)
self.cellSize = cellSize
self.grid = []
for row in range(rowNumber):
line = []
for column in range(columnNumber):
line.append(Cell(self, column, row, cellSize))
self.grid.append(line)
#memorize the cells that have been modified to avoid many switching of state during mouse motion.
self.switched = []
#bind click action
self.bind("<Button-1>", self.handleMouseClick)
#bind moving while clicking
self.bind("<B1-Motion>", self.handleMouseMotion)
#bind release button action - clear the memory of midified cells.
self.bind("<ButtonRelease-1>", lambda event: self.switched.clear())
self.draw()
def draw(self):
for row in self.grid:
for cell in row:
cell.draw()
def _eventCoords(self, event):
row = int(event.y / self.cellSize)
column = int(event.x / self.cellSize)
return row, column
def handleMouseClick(self, event):
row, column = self._eventCoords(event)
cell = self.grid[row][column]
cell._switch()
cell.draw()
#add the cell to the list of cell switched during the click
self.switched.append(cell)
def handleMouseMotion(self, event):
row, column = self._eventCoords(event)
cell = self.grid[row][column]
if cell not in self.switched:
cell._switch()
cell.draw()
self.switched.append(cell)
#Game of Life Code Begins Here
def invert(grid):
for i in grid.grid:
for j in i:
j._switch()
j.draw()
grid.update()
def clear(app, grid):
#Get Current Height and Width from grid list
height = len(grid.grid)
width = len(grid.grid[0]) #The length of the row (width) within the column list
for i in grid.grid:
for j in i:
j.fill = False
j.draw()
grid.update()
def export_schematic(grid):
#Get Current Height and Width from grid list
height = len(grid.grid)
width = len(grid.grid[0])
#Save all current grid values into the gridlist
gridlist = {}
for i in grid.grid:
for j in i:
gridlist[j.abs, j.ord] = j.fill
fout = filedialog.asksaveasfile(mode='w', defaultextension=".txt", initialdir = "C:\\", title = "Select file", filetypes = (("Text files","*.txt"),("all files","*.*")))
gridlist = dict([(str(i),j) for i,j in gridlist.items()])
export_dictionary = {"size": (height, width), "values": gridlist}
fout.write(json.dumps(export_dictionary))
fout.close()
def import_schematic(app, grid):
fin = filedialog.askopenfilename(defaultextension=".txt", initialdir = "C:\\", title = "Select file", filetypes = (("Text files","*.txt"),("all files","*.*")))
with open(fin, 'r') as f:
data = json.load(f)
grid_size = data["size"]
height = grid_size[0]
width = grid_size[1]
grid_values = data['values']
grid_values_dict = dict([(eval(str(i)),j) for i,j in grid_values.items()])
app.destroy()
main(height, width, grid_values_dict)
def create_window(app):
window = Toplevel(app)
label2 = Label(window, text="Settings").grid(row=1, column=1)
label3 = Label(window, text='Height of Grid').grid(row=2, column=1)
height = Entry(window)
height.grid(row=2, column=2)
height.insert(0,25)
label4 = Label(window, text="Width of Grid").grid(row=3, column=1)
width = Entry(window)
width.grid(row=3, column=2)
width.insert(0,25)
button6 = Button(window, text="Accept and Reset", command= lambda : reset(app, height.get(), width.get())).grid(row=4, column=1)
def reset(app, height=None, width=None):
height = int(height)
width = int(width)
app.destroy()
main(height, width)
def game_of_life(grid, lgt):
len = int(lgt.get())
for l in range(len):
indices = {}
for i in grid.grid:
for j in i:
live = 0
pos = i.index(j)
try:
up = grid.grid[grid.grid.index(i)-1]
down = grid.grid[grid.grid.index(i)+1]
topl = up[pos-1]
top = up[pos]
topr = up[pos+1]
left = i[pos-1]
right = i[pos+1]
botl = down[pos-1]
bot = down[pos]
botr = down[pos+1]
except:
pass
if topl.fill == True:
live+=1
if top.fill == True:
live+=1
if topr.fill == True:
live+=1
if left.fill == True:
live+=1
if right.fill == True:
live+=1
if botl.fill == True:
live+=1
if bot.fill == True:
live+=1
if botr.fill == True:
live+=1
indices[(j.abs, j.ord)] = live
#Store variable live and assign to index value, dictionary?
#Calculate in second for loop
for i in grid.grid:
for j in i:
live = indices[(j.abs, j.ord)]
if j.fill == True and live == 2 or live == 3:
pass
if j.fill == True and live<2:
j.fill = False
if j.fill == True and live>3:
j.fill = False
if j.fill == False and live == 3:
j.fill = True
j.draw()
grid.update()
grid.delete(ALL)
invert(grid)
invert(grid)
def main(height, width, schematic = None):
app = Tk()
app.title("Conway's Game Of Life")
grid = CellGrid(app, height, width, 10)
button_frame = Frame(app)
button_frame.pack(side="bottom", expand=False)
button = Button(button_frame, text="Commence Game of Life!", command=lambda : game_of_life(grid, lgt))
button2 = Button(app, text='Clear Grid', command = lambda : clear(app, grid))
button3 = Button(button_frame, text="Export Schematic", command = lambda : export_schematic(grid))
button4 = Button(button_frame, text='Import Schematic', command = lambda : import_schematic(app, grid))
button5 = Button(button_frame, text='Settings', command = lambda : create_window(app))
label = Label(button_frame, text="Number of Iterations").grid(row=2, column=1)
lgt = Entry(button_frame)
lgt.insert(0, 10)
grid.pack()
button.grid(row=1, column=1)
button2.pack()
button3.grid(row=2, column=3)
button4.grid(row=1, column=3)
button5.grid(row=3, column=2)
lgt.grid(row=2, column=2)
# If schematic is provided, populate the grid with the values from the scheamtic
if schematic:
for i in grid.grid:
for j in i:
if (j.abs, j.ord) in schematic:
j.fill = schematic[(j.abs, j.ord)]
j.draw()
grid.update()
app.mainloop()
if __name__ == "__main__":
defheight = 25
defwidth = 25
main(defheight,defwidth)