Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions game/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import typer

from game.utils.map import Map
from game.utils.tui import run

app = typer.Typer()

Expand All @@ -21,14 +22,14 @@ def main(
game_map = Map()
if map_grid is not None:
game_map.load_from_str(map_grid)
game_map.run()
run(game_map)


@app.command()
def from_file(file_path: str):
game_map = Map()
game_map.load_from_file(file_path)
game_map.run()
run(game_map)


if __name__ == "__main__":
Expand Down
Empty file added game/tests/cli/__init__.py
Empty file.
14 changes: 13 additions & 1 deletion game/tests/cli.py → game/tests/cli/cli.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from game.utils.map import Map
from game.utils.tui import prepare_display


def test_from_arg():
Expand Down Expand Up @@ -32,6 +33,17 @@ def test_from_arg_and_from_file_are_identical():
game_map_from_arg.load_from_str("..... .### # ....# .")

game_map_from_file = Map()
game_map_from_file.load_from_file("game/tests/test_map.txt")
game_map_from_file.load_from_file("game/tests/cli/test_map.txt")

assert game_map_from_arg.map == game_map_from_file.map


def test_tui():
game_map = Map()
game_map.load_from_file("game/tests/cli/test_map.txt")

display = prepare_display(game_map, state={"paused": False})

expected_display = open("game/tests/cli/expected_display.txt").read()

assert display == expected_display
7 changes: 7 additions & 0 deletions game/tests/cli/expected_display.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Generation: 0 Population: 5 Press (p/r/q) to pause/restart game/quit.

. . . . .
. # # # .
# . . . .
. . . . #
. . . . .
File renamed without changes.
18 changes: 3 additions & 15 deletions game/utils/map.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
import time

from rich.console import Console
from rich.live import Live


class AbstractMap:
"""
Abstract class for the map.
Expand Down Expand Up @@ -87,6 +81,7 @@ def __str__(self) -> str:
map_str = ""
for row in self.map:
map_str += "".join(["# " if cell else ". " for cell in row])
map_str = map_str.strip()
map_str += "\n"

return map_str
Expand Down Expand Up @@ -114,12 +109,13 @@ def load_from_rows(self, rows: list[str]):
self.map = [[False for _ in range(self.number_of_columns)] for _ in range(self.number_of_rows)]
for y, line in enumerate(rows):
for x, char in enumerate(line.strip()):
print(x, y, char, line)
if char == "#":
self.map[y][x] = True
elif char != ".":
raise ValueError(f"Invalid character '{char}' in map string.")

self.population = self.count_population()

def next_generation(self):
new_map = [[False for _ in range(self.number_of_columns)] for _ in range(self.number_of_rows)]
population = 0
Expand All @@ -140,11 +136,3 @@ def next_generation(self):
self.map = new_map
self.generation += 1
self.population = population

def run(self):
console = Console()
with Live(self.__str__(), refresh_per_second=5, console=console) as live:
while self.population > 0:
self.next_generation()
live.update(self.__str__())
time.sleep(0.1) # small pause between generations
71 changes: 71 additions & 0 deletions game/utils/tui.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import threading
from copy import deepcopy
from time import sleep

from pynput import keyboard
from rich.console import Console
from rich.live import Live

from game.utils.map import Map


def prepare_display(game_map: Map, state: dict) -> str:
display_str = ""
display_str += (
f"Generation: {game_map.generation} Population: {game_map.population}"
f" Press (p/r/q) to pause/restart game/quit.\n"
)
if state["paused"]:
display_str += "Paused\n\n"
else:
display_str += "\n"

display_str += str(game_map)

return display_str


def detect_key_input(state: dict, lock):
def on_press(key):
try:
if key.char == "p":
with lock:
state["paused"] = not state["paused"]
elif key.char == "r":
with lock:
state["restart"] = True
elif key.char == "q":
with lock:
state["quit"] = True
return
except AttributeError:
pass

with keyboard.Listener(on_press=on_press) as listener:
listener.join()


def run(game_map: Map):
console = Console()
starting_map = deepcopy(game_map)
state = {"paused": False, "restart": False, "quit": False}
lock = threading.Lock()

key_listener = threading.Thread(target=detect_key_input, args=(state, lock), daemon=True)
key_listener.start()

with Live(prepare_display(game_map, state), refresh_per_second=5, console=console) as live:
while game_map.population > 0:
with lock:
if state["quit"]:
return
if state["restart"]:
game_map = deepcopy(starting_map)
live.update(prepare_display(game_map, state))
state["restart"] = False

if not state["paused"]:
game_map.next_generation()

live.update(prepare_display(game_map, state))
sleep(0.1)
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ dependencies = [
"pytest>=8.4.0",
"ruff>=0.11.13",
"typer>=0.16.0",
"pynput>=1.8.1"
]

[build-system]
Expand Down
113 changes: 113 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.