-
Notifications
You must be signed in to change notification settings - Fork 0
/
life.py
86 lines (66 loc) · 2.25 KB
/
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
import time
import pygame
import numpy as np
COLOR_BG = (10, 10, 10)
COLOR_GRID = (40, 40, 40)
COLOR_DIE_NEXT = (170, 170, 170)
COLOR_ALIVE_NEXT = (255, 255, 255)
SIZE = 10
WIDTH = 1280
HEIGHT = 640
def update(screen, cells, size, with_progress=False):
updated_cells = np.zeros((cells.shape[0], cells.shape[1]))
for row, col in np.ndindex(cells.shape):
alive = np.sum(cells[row-1:row+2, col-1:col+2]) - cells[row, col]
if cells[row, col] == 0:
color = COLOR_BG
else:
color = COLOR_ALIVE_NEXT
# if the cell is alive
if cells[row, col] == 1:
if alive < 2 or alive > 3:
if with_progress:
color = COLOR_DIE_NEXT
elif 2 <= alive <= 3:
updated_cells[row, col] = 1
if with_progress:
color = COLOR_ALIVE_NEXT
else:
if alive == 3:
updated_cells[row, col] = 1
if with_progress:
color = COLOR_ALIVE_NEXT
pygame.draw.rect(screen, color, (col * size, row * size, size - 1, size - 1))
return updated_cells
def main():
pygame.init()
pygame.display.set_caption("*** THE GAME OF LIFE ***")
screen = pygame.display.set_mode((1280, 640))
cells = np.zeros((100, 150))
screen.fill(COLOR_GRID)
update(screen, cells, 10)
pygame.display.flip()
pygame.display.update()
running = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
running = not running
update(screen, cells, 10)
pygame.display.update()
if pygame.mouse.get_pressed()[0]:
pos = pygame.mouse.get_pos()
cells[pos[1] // 10, pos[0] // 10] = 1
update(screen, cells, 10)
pygame.display.update()
screen.fill(COLOR_GRID)
if running:
cells = update(screen, cells, 10, with_progress=True)
pygame.display.update()
time.sleep(0.001)
if __name__ == "__main__":
main()