-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameOfLife.py
104 lines (82 loc) · 2.76 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
from graphics import *
import time
tileSize = 10
screenXLength = 100
screenYLength = 75
win = GraphWin("Game of Life", screenXLength * tileSize, screenYLength * tileSize)
screen = [[[Rectangle(Point(x * tileSize, y * tileSize), Point((x + 1) * tileSize - 1, (y + 1) * tileSize - 1)), 0] for x in range(screenXLength)] for y in range(screenYLength)]
def getRectangle(p):
return screen[int(p.getY()) // tileSize][int(p.getX()) // tileSize]
def initScreen():
win.setBackground("light grey")
win.autoflush = False
for row in screen:
for square in row:
square[0].draw(win)
win.flush()
win.autoflush = True
while win.checkKey() == "":
sqr = getRectangle(win.getMouse())
if sqr[1] == 0:
sqr[0].setFill("black")
sqr[1] = 1
else:
sqr[0].setFill("light grey")
sqr[1] = 0
def getX(sqr):
return sqr[0].getCenter().getX() // tileSize
def getY(sqr):
return sqr[0].getCenter().getY() // tileSize
def numOfFriends(square, list):
counter = 0
for sqr in list:
if sqr != square:
if abs(getX(sqr) - getX(square)) <= 1 and abs(getY(sqr) - getY(square)) <= 1:
counter += 1
return counter
def getFriends(square):
friends = []
for x in range(-1,2):
for y in range(-1,2):
if int(getY(square)) + y <screenYLength and int(getX(square)) + x < screenXLength:
if screen[y + int(getY(square))][x + int(getX(square))] != square:
friends.append(screen[y + int(getY(square))][x + int(getX(square))])
return friends
def deleteDups(list):
result = []
for elem in list:
if elem not in result:
result.append(elem)
return result
def start():
iteration = 0
blacked = []
for row in screen:
for square in row:
if square[1] == 1: blacked.append(square)
while win.checkKey() == "":
newBlacked = []
for black in blacked:
if black[1] == 1 and (numOfFriends(black, blacked) == 3 or numOfFriends(black, blacked) == 2):
newBlacked.append(black)
for friend in getFriends(black):
if friend[1] == 0 and numOfFriends(friend, blacked) == 3:
newBlacked.append(friend)
# win.autoflush = False
newBlacked = deleteDups(newBlacked)
for black in blacked:
black[0].setFill("light grey")
black[1] = 0
for newBlack in newBlacked:
newBlack[0].setFill("black")
newBlack[1] = 1
blacked = newBlacked
# win.flush()
# win.autoflush = True
iteration += 1
print(iteration)
time.sleep(0.2)
def main():
initScreen()
start()
main()