Files
board-mate/rpi/services/game_service.py
2026-01-05 20:17:53 +01:00

69 lines
2.0 KiB
Python

import json
from typing import Callable
from hardware.buzzer.buzzer import Buzzer
from hardware.camera.camera import Camera
from hardware.led.led import Led
from models.exceptions.ServiceException import ServiceException
from models.game import Game
from services.clock_service import ClockService
class GameService:
_game : Game
_camera : Camera
_clock_service : ClockService
_led : Led
_buzzer : Buzzer
_on_terminated : Callable[[str], None]
_has_started : bool
def __init__(self):
self._camera = Camera()
self._clock_service = ClockService()
self._led = Led(7)
self._buzzer = Buzzer(8)
self._has_started = False
def start(self, white_name, back_name, time_control : int, increment : int, timestamp : int) -> None:
if self._has_started :
raise ServiceException("Game has already started.")
try :
self._game = Game(white_name, back_name, time_control, increment, timestamp)
self._clock_service.start(time_control, increment)
self._clock_service.set_on_terminated(self.stop)
self._led.on()
self._has_started = True
except Exception as e:
print(e)
raise ServiceException(e)
def stop(self):
self._clock_service.stop()
self._led.off()
self._notify()
self._has_started = False
def make_move(self) -> bytes:
try :
if not self._has_started :
raise Exception("Game hasn't started yet.")
self._clock_service.switch()
img = self._camera.take_photo()
return img
except Exception as e:
print(e)
raise ServiceException(e)
def add_move(self, fen):
self._game.add_move(fen)
def set_on_terminated(self, callback: Callable[[str], None]):
self._on_terminated = callback
def _notify(self):
game_data = json.dumps(self._game.to_dict())
self._on_terminated(game_data)