-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame_of_life.py
116 lines (81 loc) · 3.03 KB
/
game_of_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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"""An implementation of the Game of Life."""
import itertools
import sys
import time
import pygame
from pygame.locals import K_RETURN, KEYDOWN, QUIT
WIDTH = 700
HEIGHT = 700
def get_alive(matrix):
return sum(sum(row) for row in matrix)
def is_valid(x_cord, y_cord, size):
return min(x_cord, y_cord) >= 0 and max(x_cord, y_cord) < size
def handle(event):
if event.type == QUIT:
pygame.quit()
sys.exit()
def draw(matrix, size):
black_color = (0, 0, 0)
grey_color = (105, 105, 105)
white_color = (255, 255, 255)
game_display.fill(white_color)
for row in range(size):
for col in range(size):
if matrix[row][col] == 1:
rect = pygame.Rect(col * (HEIGHT // size), row *
(HEIGHT // size), HEIGHT // size, HEIGHT // size)
pygame.draw.rect(game_display, black_color, rect)
for row in range(size + 1):
pygame.draw.line(game_display, grey_color,
(row * (HEIGHT // size), 0), (row * (HEIGHT // size), WIDTH), width=1)
for col in range(size + 1):
pygame.draw.line(game_display, grey_color,
(0, col * (WIDTH // size)), (HEIGHT, col * (WIDTH // size)), width=1)
pygame.display.update()
def setup(matrix, size):
print("Place initial disposition of alive cells")
draw(matrix, size)
initial_setup = True
while initial_setup:
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_RETURN:
initial_setup = False
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
i = pos[1] // (HEIGHT // size)
j = pos[0] // (HEIGHT // size)
matrix[i][j] = 1
draw(matrix, size)
if __name__ == '__main__':
size = int(input('Enter dimension of the system: '))
matrix = [[0] * size for _ in range(size)]
dx = [1, 1, -1, -1, 0, 0, 1, -1]
dy = [1, -1, 1, -1, 1, -1, 0, 0]
pygame.init()
game_display = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.flip()
setup(matrix, size)
while get_alive(matrix) > 0:
for event in pygame.event.get():
handle(event)
draw(matrix, size)
transition = [[0] * size for _ in range(size)]
for row, col in itertools.product(range(size), range(size)):
alive = 0
for k in range(8):
nx = row + dx[k]
ny = col + dy[k]
if is_valid(nx, ny, size):
alive += matrix[nx][ny]
if matrix[row][col] == 1 and alive in [2, 3]:
transition[row][col] = 1
if matrix[row][col] == 0 and alive == 3:
transition[row][col] = 1
for row in range(size):
for col in range(size):
matrix[row][col] = transition[row][col]
time.sleep(0.2)
for event in pygame.event.get():
handle(event)
draw(matrix, size)
time.sleep(1)