|
| 1 | +import threading |
| 2 | +from copy import deepcopy |
| 3 | +from time import sleep |
| 4 | + |
| 5 | +from pynput import keyboard |
| 6 | +from rich.console import Console |
| 7 | +from rich.live import Live |
| 8 | + |
| 9 | +from game.utils.map import Map |
| 10 | + |
| 11 | + |
| 12 | +def prepare_display(game_map: Map, state: dict) -> str: |
| 13 | + display_str = "" |
| 14 | + display_str += ( |
| 15 | + f"Generation: {game_map.generation} Population: {game_map.population}" |
| 16 | + f" Press (p/r/q) to pause/restart game/quit.\n" |
| 17 | + ) |
| 18 | + if state["paused"]: |
| 19 | + display_str += "Paused\n\n" |
| 20 | + else: |
| 21 | + display_str += "\n" |
| 22 | + |
| 23 | + display_str += str(game_map) |
| 24 | + |
| 25 | + return display_str |
| 26 | + |
| 27 | + |
| 28 | +def detect_key_input(state: dict, lock): |
| 29 | + def on_press(key): |
| 30 | + try: |
| 31 | + if key.char == "p": |
| 32 | + with lock: |
| 33 | + state["paused"] = not state["paused"] |
| 34 | + elif key.char == "r": |
| 35 | + with lock: |
| 36 | + state["restart"] = True |
| 37 | + elif key.char == "q": |
| 38 | + with lock: |
| 39 | + state["quit"] = True |
| 40 | + return |
| 41 | + except AttributeError: |
| 42 | + pass |
| 43 | + |
| 44 | + with keyboard.Listener(on_press=on_press) as listener: |
| 45 | + listener.join() |
| 46 | + |
| 47 | + |
| 48 | +def run(game_map: Map): |
| 49 | + console = Console() |
| 50 | + starting_map = deepcopy(game_map) |
| 51 | + state = {"paused": False, "restart": False, "quit": False} |
| 52 | + lock = threading.Lock() |
| 53 | + |
| 54 | + key_listener = threading.Thread(target=detect_key_input, args=(state, lock), daemon=True) |
| 55 | + key_listener.start() |
| 56 | + |
| 57 | + with Live(prepare_display(game_map, state), refresh_per_second=5, console=console) as live: |
| 58 | + while game_map.population > 0: |
| 59 | + with lock: |
| 60 | + if state["quit"]: |
| 61 | + return |
| 62 | + if state["restart"]: |
| 63 | + game_map = deepcopy(starting_map) |
| 64 | + live.update(prepare_display(game_map, state)) |
| 65 | + state["restart"] = False |
| 66 | + |
| 67 | + if not state["paused"]: |
| 68 | + game_map.next_generation() |
| 69 | + |
| 70 | + live.update(prepare_display(game_map, state)) |
| 71 | + sleep(0.1) |
0 commit comments