-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
108 lines (92 loc) · 3.27 KB
/
game.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
from pygame.locals import QUIT, Rect
import numpy as np
import random
import pygame
import sys
class Board:
def __init__(self, grid_size, cell_size):
self.FPS = 10
self.dead_color = (255, 255, 255)
self.alive_color = (148, 0, 211)
self.grid_size = grid_size
self.cell_size = cell_size
self.window_size = (self.grid_size * self.cell_size) - 1
self.grid = {
(x * self.cell_size, y * self.cell_size): random.choice(
[self.dead_color, self.alive_color]
)
for x in range(self.grid_size)
for y in range(self.grid_size)
}
pygame.init()
pygame.display.set_caption("Game of Life")
self.screen = pygame.display.set_mode((self.window_size, self.window_size))
self.screen.fill((255, 255, 255))
def __draw(self):
for coords, color in self.grid.items():
x, y = coords
radius = self.cell_size // 2
x = x + radius
y = y + radius
pygame.draw.circle(self.screen, color, (x, y), self.cell_size // 2)
def __count_neighbors(self, coords):
coords = np.array([coords] * 8)
directions = np.array(
[
(0, -self.cell_size),
(self.cell_size, -self.cell_size),
(-self.cell_size, -self.cell_size),
(0, self.cell_size),
(self.cell_size, self.cell_size),
(-self.cell_size, self.cell_size),
(self.cell_size, 0),
(-self.cell_size, 0),
]
)
neighbors = []
for direction in (coords + directions).tolist():
if (
len(
[
x
for x in direction
if x >= 0 and x < self.cell_size * self.grid_size
]
)
< 2
):
neighbors.append(self.dead_color)
else:
neighbors.append(self.grid[tuple(direction)])
return neighbors.count(self.alive_color)
def __apply_rules(self):
new_grid = {}
for coords in self.grid:
if self.grid[coords] == self.dead_color:
n = self.__count_neighbors(coords)
if n == 3:
new_grid[coords] = self.alive_color
else:
new_grid[coords] = self.dead_color
if self.grid[coords] == self.alive_color:
n = self.__count_neighbors(coords)
if n < 2:
new_grid[coords] = self.dead_color
elif n > 3:
new_grid[coords] = self.dead_color
else:
new_grid[coords] = self.alive_color
self.grid = new_grid
def create_life(self):
fps_clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
self.__apply_rules()
self.__draw()
pygame.display.update()
fps_clock.tick(self.FPS)
if __name__ == "__main__":
Board(grid_size=80, cell_size=6).create_life()