-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConway.py
78 lines (53 loc) · 2.51 KB
/
Conway.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
import sys
import time
from collections import defaultdict
from copy import deepcopy
import pygame
from collections import namedtuple
Dim = namedtuple("Dimension", ["width", "height"])
Grid = namedtuple("Grid", ["dim", "cells"])
Neighbours = namedtuple("Neighbours", ["alive", "dead"])
Grid_shape = Grid(Dim(50, 50), {(22, 8), (12, 7), (36, 7), (17, 9), (11, 8), (1, 9), (25, 4), (2, 8), (16, 7),
(25, 10), (21, 6), (23, 9), (14, 6), (36, 6), (22, 7), (14, 12), (17, 8), (11, 10),
(25, 9), (35, 7), (1, 8), (18, 9), (22, 6), (21, 8), (23, 5), (12, 11), (17, 10),
(11, 9), (35, 6), (25, 5), (2, 9), (13, 6), (13, 12), (15, 9), (16, 11), (21, 7)})
def get_neighbours(grid: Grid, x: int, y: int) -> Neighbours:
offsets = [(-1, -1), (0, -1), (1, -1), (-1, 0),
(1, 0), (-1, 1), (0, 1), (1, 1)]
possible_neighbours = {(x + x_add, y + y_add) for x_add, y_add in offsets}
alive = {(pos[0], pos[1])
for pos in possible_neighbours if pos in grid.cells}
return Neighbours(alive, possible_neighbours - alive)
def update_grid(grid: Grid) -> Grid:
new_cells = deepcopy(grid.cells)
undead = defaultdict(int)
for (x, y) in grid.cells:
alive_neighbours, dead_neighbours = get_neighbours(grid, x, y)
if len(alive_neighbours) not in [2, 3]:
new_cells.remove((x, y))
for pos in dead_neighbours:
undead[pos] += 1
for pos, _ in filter(lambda elem: elem[1] == 3, undead.items()):
new_cells.add((pos[0], pos[1]))
return Grid(grid.dim, new_cells)
def draw_grid(screen: pygame.Surface, grid: Grid) -> None:
cell_width = screen.get_width() / grid.dim.width
cell_height = screen.get_height() / grid.dim.height
border_size = 2
for (x, y) in grid.cells:
pygame.draw.rect(screen, (255, 0, 0), (x * cell_width + border_size, y * cell_height +
border_size, cell_width - border_size, cell_height - border_size))
def main():
grid = Grid_shape
pygame.init()
screen = pygame.display.set_mode((600, 400))
while True:
if pygame.QUIT in [e.type for e in pygame.event.get()]:
sys.exit(0)
screen.fill((0, 0, 0))
draw_grid(screen, grid)
grid = update_grid(grid)
pygame.display.flip()
time.sleep(0.1)
if __name__ == "__main__":
main()