-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
90 lines (69 loc) · 2.72 KB
/
main.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
import time
import numpy as np
import pygame
COLOR_BG = (10, 10, 10)
COLOR_GRID = (40, 40, 40)
COLOR_DIE_NEXT = (170, 170, 170)
COLOR_ALIVE_NEXT = (255, 255, 255)
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]
color = COLOR_BG if cells[row, col] == 0 else COLOR_ALIVE_NEXT
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()
screen = pygame.display.set_mode((800, 600))
cells = np.zeros((60, 80))
screen.fill(COLOR_GRID)
update(screen, cells, 10)
pygame.display.flip()
pygame.display.update()
running = False
while True:
events = pygame.event.get() # Get all pending events
for event in events:
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()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == pygame.BUTTON_LEFT: # Left mouse button pressed
pos = pygame.mouse.get_pos()
cells[pos[1] // 10, pos[0] // 10] = 1 # Set the cell to 1
elif event.button == pygame.BUTTON_RIGHT: # Right mouse button pressed
pos = pygame.mouse.get_pos()
cells[
pos[1] // 10, pos[0] // 10
] = 0 # Set the cell to 0 to delete it
# Check if the left mouse button is held down
if pygame.mouse.get_pressed()[0]:
pos = pygame.mouse.get_pos()
cells[pos[1] // 10, pos[0] // 10] = 1 # Set the cell to 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.1)
if __name__ == "__main__":
main()