-
Notifications
You must be signed in to change notification settings - Fork 1
/
GameOfLife.py
71 lines (53 loc) · 2.5 KB
/
GameOfLife.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
################################################################################
"""A minimalist implementation of the Game of Life cellular automaton."""
__author__ = "Carlos Luna-Mota"
__license__ = "The Unlicense"
__version__ = "20220825"
__all__ = ["next_GameOfLife", "read_GameOfLife", "show_GameOfLife"]
################################################################################
from collections import defaultdict
def next_GameOfLife(universe):
"""Performs a single iteration of Game of Life in a boundless universe."""
candidates = defaultdict(int)
for (x,y) in universe:
for (dx,dy) in (0,1),(1,0),(0,-1),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1):
candidates[x+dx,y+dy] += 1
new_universe = set()
for cell,neighbors in candidates.items():
if neighbors == 3 or (neighbors == 2 and cell in universe):
new_universe.add(cell)
return new_universe
def read_GameOfLife(pattern, origin=(0,0), alive='O'):
"""Reads a pattern and return its set of live cells."""
universe = set()
for y,row in enumerate(pattern):
for x,cell in enumerate(row):
if cell == alive: universe.add((origin[0]+x, origin[1]+y))
return universe
def show_GameOfLife(universe, X, Y):
"""Prints a rectangular window of the universe on the screen."""
print('╔' + '═' * (2*len(x_range) + 1) + '╗')
for y in Y: print('║ '+' '.join(' ■'[(x,y) in universe] for x in X)+' ║')
print('╚' + '═' * (2*len(x_range) + 1) + '╝')
################################################################################
if __name__ == '__main__':
# Settings:
x_range = range(-3,10)
y_range = range(-6,12)
pattern = ("..OOO..", ##########################
"..O.O..", # #
"..O.O..", # RIP John Conway #
"...O...", # (1937-2020) #
"O.OOO..", # #
".O.O.O.", # https://xkcd.com/2293/ #
"...O..O", # #
"..O.O..", ##########################
"..O.O..")
# Main loop:
universe = read_GameOfLife(pattern)
while True:
show_GameOfLife(universe, x_range, y_range)
universe = next_GameOfLife(universe)
wait = input("\nPress <Return> to perform a step.")
print("\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A")
################################################################################