-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlife.py
More file actions
executable file
·187 lines (158 loc) · 6.17 KB
/
Copy pathlife.py
File metadata and controls
executable file
·187 lines (158 loc) · 6.17 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python3
#[x-cmds]: UPDATE
"""Conway's game of life in the console."""
from typing import Optional
from xulbux.base.consts import CHARS
from xulbux import FormatCodes, Console
import random
import time
import sys
ARGS = Console.get_args({"help": {"-h", "--help"}})
def print_help():
help_text = """
[b|in|bg:black]( Game of Life — [link:https://wikipedia.org/wiki/Conway's_Game_of_Life](Conway's cellular automaton) in the terminal )
[b](Usage:) [br:green](life)
[b](Controls:)
[br:red](Ctrl(⌘)[dim](+)C) Exit the simulation
[b](Examples:)
[br:green](life) [dim](# [i](Start Game of Life with interactive setup))
"""
FormatCodes.print(help_text)
class GameOfLife:
def __init__(self):
self.width = Console.width
self.height = Console.height * 2
self.grid = [[False for _ in range(self.width)] for _ in range(self.height)]
self.next_grid = [[False for _ in range(self.width)] for _ in range(self.height)]
# PRE-COMPUTE UTF-8 BYTE SEQUENCES FOR MAXIMUM EFFICIENCY
self.c_full = "█".encode("utf-8")
self.c_upper = "▀".encode("utf-8")
self.c_lower = "▄".encode("utf-8")
self.c_empty = " ".encode("utf-8")
def initialize_random(self, density: float = 0.3) -> None:
for y in range(self.height):
for x in range(self.width):
self.grid[y][x] = random.random() < density
def count_neighbors(self, x: int, y: int) -> int:
count = 0
for dy in [-1, 0, 1]:
for dx in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
nx, ny = x + dx, y + dy
if 0 <= nx < self.width and 0 <= ny < self.height:
if self.grid[ny][nx]:
count += 1
return count
def update(self) -> None:
for y in range(self.height):
for x in range(self.width):
neighbors = self.count_neighbors(x, y)
current_state = self.grid[y][x]
if current_state:
self.next_grid[y][x] = neighbors in [2, 3]
else:
self.next_grid[y][x] = neighbors == 3
self.grid, self.next_grid = self.next_grid, self.grid
def render(self) -> None:
frame = bytearray()
for i, row in enumerate(range(0, self.height - 1, 2)):
line = bytearray()
for col in range(self.width):
upper_filled = self.grid[row][col]
lower_filled = self.grid[row + 1][col]
if upper_filled and lower_filled: char_bytes = self.c_full
elif upper_filled: char_bytes = self.c_upper
elif lower_filled: char_bytes = self.c_lower
else: char_bytes = self.c_empty
line.extend(char_bytes)
frame.extend(line)
if i < (self.height - 1) // 2 - 1:
frame.extend(b"\n")
sys.stdout.write(f"\x1bc{frame.decode('utf-8')}")
def add_glider(self, x: int, y: int) -> None:
glider = [
[False, True, False],
[False, False, True],
[True, True, True],
]
for dy in range(3):
for dx in range(3):
nx, ny = x + dx, y + dy
if 0 <= nx < self.width and 0 <= ny < self.height:
self.grid[ny][nx] = glider[dy][dx]
def add_oscillator(self, x: int, y: int) -> None:
if 0 <= x < self.width and 0 <= y - 1 < self.height and 0 <= y + 1 < self.height:
self.grid[y - 1][x] = True
self.grid[y][x] = True
self.grid[y + 1][x] = True
def run(self, gens: Optional[int] = None, delay: float = 0.05) -> None:
try:
gen = 0
while gens is None or gen < gens:
new_width = Console.width
new_height = Console.height * 2
if new_width != self.width or new_height != self.height:
old_grid = self.grid
self.width = new_width
self.height = new_height
self.grid = [[False for _ in range(self.width)] for _ in range(self.height)]
self.next_grid = [[False for _ in range(self.width)] for _ in range(self.height)]
for y in range(min(len(old_grid), self.height)):
for x in range(min(len(old_grid[0]), self.width)):
self.grid[y][x] = old_grid[y][x]
self.render()
self.update()
gen += 1
time.sleep(delay)
except KeyboardInterrupt:
sys.stdout.write("\x1bc")
def main():
if ARGS.help.exists:
print_help()
return
game = GameOfLife()
FormatCodes.print("[b](Choose Initialization)\n"
" [b|i](1) Random pattern\n"
" [b|i](2) Some classic patterns")
choice = Console.input(
"(1) [b](>) ",
max_len=1,
allowed_chars="12",
default_val=1,
output_type=int,
)
match choice:
case 2:
game.add_glider(5, 5)
game.add_glider(15, 8)
game.add_oscillator(25, 10)
game.add_oscillator(30, 15)
for _ in range(20):
x = random.randint(0, game.width - 1)
y = random.randint(0, game.height - 1)
game.grid[y][x] = True
case _:
density = 0.2
density = Console.input(
f"\n[b](Enter density) [0.0 – 1.0]({density}) [b](>) ",
allowed_chars=CHARS.FLOAT_DIGITS,
default_val=density,
output_type=float,
)
game.initialize_random(max(0.0, min(1.0, density)))
delay = 0.02
delay = Console.input(
f"\n[b](Delay between generations) [secs]({delay}) [b](>) ",
allowed_chars=CHARS.FLOAT_DIGITS,
default_val=delay,
output_type=float,
)
game.run(delay=max(0, delay))
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print()
except Exception as exc:
Console.fail(exc, start="\n", end="\n\n")