""" Module defining a class to store the games/rooms in the different languages. """ from dataclasses import dataclass import logging from typing import Dict, List import pkg_resources from swiftstory.exception import UnsupportedLanguage from swiftstory.game import Game from swiftstory.cards import Cards class NoSuchGameError(Exception): """ Exception to be raised when no game is found matching the criterion. """ def __init__(self, message: str = "", game_name: str = "", lang: str = "") -> None: self.game_name = game_name self.lang = lang super().__init__(message) @dataclass class LangContainer: """ Container for game objects in a given language. """ black_cards: List[str] white_cards: List[str] games: Dict[str, Game] class GameManager: """ Store the different rooms/games of the different languages. """ def __init__(self) -> None: self.lang_containers: Dict[str, LangContainer] = {} for language in self.list_languages(): self.lang_containers[language] = LangContainer( black_cards=Cards.get_black_cards(language), white_cards=Cards.get_white_cards(language), games={} ) @staticmethod def list_languages() -> List[str]: """ List available languages based on FS. """ return pkg_resources.resource_listdir(__name__, "data/lang") def find_by_name(self, game_name: str, lang: str, create: bool = True) -> Game: """ Find and return the game that matches the name and language specified. If the game does not exist but create is set to True, a new game will be created. """ container = self.lang_containers.get(lang) if container is None: raise UnsupportedLanguage(lang) games = container.games black_cards = container.black_cards white_cards = container.white_cards game = games.get(game_name) if game is None and not create: raise NoSuchGameError(game_name=game_name, lang=lang) if game is None: logging.info("Starting new game: %s (lang: %s)", game_name, lang) game = games[game_name] = Game(white_cards, black_cards) return game