-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgameoflife.py
110 lines (91 loc) · 2.82 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
import Tkinter as tk
import random
Filename = "initialSetup1.txt"
world = []
canvas = None
rows = 0
cols = 0
def init_board(filename):
global world, cols, rows
with open(filename, "r") as f:
cols = int(f.readline())
rows = int(f.readline())
for i in xrange(rows):
world.append([False]*cols)
a = 0
b = 0
for line in f.readlines():
for chr in line:
if chr == "*":
world[b][a] = True
elif chr == ".":
world[b][a] = False
b += 1
b = 0
a += 1
create_board()
def callback(event):
canvas.focus_set()
world[event.x/10][event.y/10] = True
print "clicked at", event.x, event.y
def create_board():
global window, canvas, world
window = tk.Tk()
canvas = tk.Canvas(window, width=cols*10, height=rows*10, bg='grey')
canvas.bind("<Button-1>", callback)
canvas.bind("<Button-2>", paus)
canvas.bind("<B1-Motion>", callback)
canvas.pack(expand=tk.YES, fill=tk.BOTH)
update()
def new_world():
global world, rows, cols
nw = []
for x in xrange(rows):
a = []
for y in xrange(cols):
neighbours = []
if x + 1 < rows: # bottom
neighbours.append(world[x+1][y])
if x - 1 >= 0: # top
neighbours.append(world[x-1][y])
if y - 1 >= 0: # left
neighbours.append(world[x][y-1])
if y + 1 < cols: # right
neighbours.append(world[x][y+1])
if x + 1 < rows and y + 1 < cols: # bottom right
neighbours.append(world[x+1][y+1])
if x - 1 >= 0 and y - 1 >= 0: # top left
neighbours.append(world[x-1][y-1])
if y - 1 >= 0 and x + 1 < rows: # bottom left
neighbours.append(world[x+1][y-1])
if y + 1 < cols and x - 1 >= 0: # top right
neighbours.append(world[x-1][y+1])
res = len([n for n in neighbours if n])
if res < 2 or res > 3:
a.append(False)
elif res == 3:
a.append(True)
elif res == 2:
a.append(world[x][y])
nw.append(a)
world = nw
def draw_world(world):
global rows, cols, canvas
canvas.delete('all')
colors = ["white"]
for x in xrange(rows):
for y in xrange(cols):
c = random.choice(colors)
fill = c if world[x][y] else 'black'
canvas.create_oval(x*10, y*10, x*10+10, y*10+10, fill=fill, outline='blue')
def update():
global world, window
draw_world(world)
new_world()
window.after(10, update)
def paus():
global world, window
print "paus"
window.after_cancel
init_board(Filename)
window.mainloop()