-
Notifications
You must be signed in to change notification settings - Fork 5
/
example-03-life.py
93 lines (84 loc) · 2 KB
/
example-03-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
"""
An implementation of Conway's Game of Life.
"""
import gamelib
# size in pixels of a single cell
CELL_SIZE = 10
def life_create(map):
life = []
for r in map:
row = []
for c in r:
row.append(c == '#')
life.append(row)
return life
def neighbors(life, r, c):
amount = 0
for dr, dc in (
(-1, -1),
(0, -1),
(1, -1),
(-1, 0),
(1, 0),
(-1, 1),
(0, 1),
(1, 1),
):
nf = (r + dr) % len(life)
cell = life[nf][(c + dc) % len(life[nf])]
if cell:
amount += 1
return amount
def cell_next(life, r, c):
cell = life[r][c]
n = neighbors(life, r, c)
if not cell:
# reproduction
return n == 3
if n < 2:
# death by solitude
return False
if n in (2, 3):
# happy case
return True
# death by overpopulation
return False
def life_next(life):
life_new = []
for r in range(len(life)):
row = []
for c in range(len(life[0])):
row.append(cell_next(life, r, c))
life_new.append(row)
return life_new
def draw(life):
gamelib.draw_begin()
for y, row in enumerate(life):
for x, cell in enumerate(row):
if cell:
gamelib.draw_rectangle(
x * CELL_SIZE,
y * CELL_SIZE,
x * CELL_SIZE + CELL_SIZE,
y * CELL_SIZE + CELL_SIZE,
fill='white',
)
gamelib.draw_end()
def main():
gamelib.title("Game of life")
life = life_create([
'..........',
'..........',
'..........',
'.....#....',
'......#...',
'....###...',
'..........',
'..........',
])
gamelib.resize(len(life[0]) * CELL_SIZE, len(life) * CELL_SIZE)
while gamelib.is_alive():
draw(life)
gamelib.wait(gamelib.EventType.KeyPress)
life = life_next(life)
gamelib.init(main)