Skip to content

Commit 311afba

Browse files
authored
Merge pull request Shahrayar123#48 from TERNION-1121/master
Adding a new project/game: Game of Life
2 parents 0d35c5a + 8b811e8 commit 311afba

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

Conway's Game of Life/game_of_life.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import pygame
2+
import numpy as np
3+
4+
COLOR_BG = (10,10,10)
5+
COLOR_GRID = (40,40,40)
6+
COLOR_DIE_NEXT = (170,170,170)
7+
COLOR_ALIVE_NEXT = (255,255,255)
8+
TICK_SPEED = 30
9+
10+
clock = pygame.time.Clock()
11+
12+
def update(screen, cells, size, with_progress = False):
13+
updated_cells = np.zeros((cells.shape[0], cells.shape[1]))
14+
15+
for row,col in np.ndindex(cells.shape):
16+
alive = np.sum(cells[row-1:row+2, col-1:col+2]) - cells[row, col]
17+
color = COLOR_BG if cells[row, col] == 0 else COLOR_ALIVE_NEXT
18+
19+
if cells[row, col] == 1:
20+
if alive < 2 or alive > 3:
21+
if with_progress:
22+
color = COLOR_DIE_NEXT
23+
elif 2 <= alive <= 3:
24+
updated_cells[row, col] = 1
25+
if with_progress:
26+
color = COLOR_ALIVE_NEXT
27+
else:
28+
if alive == 3:
29+
updated_cells[row, col] = 1
30+
if with_progress:
31+
color = COLOR_ALIVE_NEXT
32+
33+
pygame.draw.rect(screen, color, (col*size, row*size, size - 1, size - 1))
34+
35+
return updated_cells
36+
37+
def main():
38+
pygame.init()
39+
screen = pygame.display.set_mode((800,600))
40+
41+
cells = np.zeros((60, 80))
42+
screen.fill(COLOR_GRID)
43+
44+
update(screen, cells, 10)
45+
46+
pygame.display.update()
47+
48+
running = False
49+
50+
while True:
51+
for event in pygame.event.get():
52+
if event.type == pygame.QUIT:
53+
pygame.quit()
54+
return
55+
elif event.type == pygame.KEYDOWN:
56+
if event.key == pygame.K_SPACE:
57+
running = not running
58+
update(screen, cells, 10)
59+
pygame.display.update()
60+
if pygame.mouse.get_pressed()[0]:
61+
pos = pygame.mouse.get_pos()
62+
cells[pos[1]//10, pos[0]//10] = 1 # cells = np.ones((cells.shape[0], cells.shape[1])) # -> fun line of code :p
63+
update(screen, cells, 10)
64+
pygame.display.update()
65+
66+
screen.fill(COLOR_GRID)
67+
68+
if running:
69+
cells = update(screen, cells, 10, with_progress = True)
70+
pygame.display.update()
71+
72+
clock.tick(TICK_SPEED)
73+
74+
if __name__ == '__main__':
75+
main()

0 commit comments

Comments
 (0)