from .game import Game from . import menu from .command import Command import os import logging import pygame from .serial import Serial import json from .games import benchmark from .games.snake import Snake from .games.breakout import Breakout from .games.pong import Pong def main() -> int: logger = logging.getLogger(__name__) pygame.init() serial = Serial(os.getenv("SERIAL_DEVICE", "/dev/null"), 115200) INSTANCE = os.getenv("INSTANCE", "Unknown") pygame.display.set_caption(f"SplitScreen Duo Menu ({INSTANCE})") logging.basicConfig( level=(logging.DEBUG if os.getenv("DEVELOPMENT", "").lower() else logging.INFO) ) print("The Dual Screen Console") logger.info(f"running as {os.getenv('INSTANCE', 'unknown')}") menu.init_display() game_handlers = { Game.BENCHMARK.value: ( "benchmark", lambda: benchmark.main_loop(menu.screen, serial), ), Game.SNAKE.value: ( "snake", lambda: Snake(menu.screen, serial, INSTANCE).main_loop(), ), Game.BREAKOUT.value: ( "breakout", lambda: Breakout(menu.screen, serial, INSTANCE).main_loop(), ), Game.PONG.value: ( "pong", lambda: Pong(menu.screen, serial, INSTANCE).main_loop(), ), } def handle_game_selection(message_or_command, is_secondary=False): game_value = message_or_command.get("value") if game_value in game_handlers: game_name, game_func = game_handlers[game_value] logger.info( f"{'received' if is_secondary else 'starting'} {game_name} game selection from {'primary' if is_secondary else 'menu'}" ) game_result = game_func() if game_result and game_result.get("command") == Command.QUIT.value: logger.info(f"{game_name} game returned QUIT, shutting down") pygame.quit() return 0 return None is_running = True while is_running: if INSTANCE == "secondary" and serial.in_waiting() > 0: try: data = serial.readline().decode("utf-8").strip() logger.debug(f"received serial data: {data}") message = json.loads(data) if message.get("command") == Command.QUIT.value: logger.info("received quit command from primary, shutting down") pygame.quit() return 0 elif message.get("command") == Command.SELECT_GAME.value: result = handle_game_selection(message, is_secondary=True) if result == 0: return 0 except json.JSONDecodeError: logger.error("failed to decode serial message") except Exception as e: logger.error(f"error processing serial data: {e}") serial_command = menu.process_events(serial, INSTANCE) if serial_command: serial.write(json.dumps(serial_command).encode("utf-8")) if serial_command.get("command") == Command.QUIT.value: logger.info("primary sent quit, shutting down") pygame.quit() return 0 elif serial_command.get("command") == Command.SELECT_GAME.value: result = handle_game_selection(serial_command) if result == 0: return 0 menu.draw_menu() pygame.quit() return 0