|
| 1 | +from dataclasses import dataclass |
| 2 | + |
| 3 | +from ttt.application.common.ports.emojis import Emojis |
| 4 | +from ttt.application.common.ports.map import Map |
| 5 | +from ttt.application.common.ports.randoms import Randoms |
| 6 | +from ttt.application.common.ports.transaction import Transaction |
| 7 | +from ttt.application.common.ports.uuids import UUIDs |
| 8 | +from ttt.application.game.common.ports.game_views import GameViews |
| 9 | +from ttt.application.game.common.ports.games import Games |
| 10 | +from ttt.application.game.common.ports.waiting_locations import WaitingLocations |
| 11 | +from ttt.application.user.common.ports.user_views import UserViews |
| 12 | +from ttt.application.user.common.ports.users import Users |
| 13 | +from ttt.entities.core.game.ai import AiType |
| 14 | +from ttt.entities.core.game.game import start_game_with_ai |
| 15 | +from ttt.entities.core.user.location import UserLocation |
| 16 | +from ttt.entities.core.user.user import UserAlreadyInGameError |
| 17 | +from ttt.entities.tools.tracking import Tracking |
| 18 | + |
| 19 | + |
| 20 | +@dataclass(frozen=True, unsafe_hash=False) |
| 21 | +class StartGameWithAi: |
| 22 | + map_: Map |
| 23 | + uuids: UUIDs |
| 24 | + emojis: Emojis |
| 25 | + randoms: Randoms |
| 26 | + users: Users |
| 27 | + user_views: UserViews |
| 28 | + games: Games |
| 29 | + game_views: GameViews |
| 30 | + waiting_locations: WaitingLocations |
| 31 | + transaction: Transaction |
| 32 | + |
| 33 | + async def __call__(self, location: UserLocation, ai_type: AiType) -> None: |
| 34 | + game_id = await self.uuids.random_uuid() |
| 35 | + ai_id = await self.uuids.random_uuid() |
| 36 | + cell_id_matrix = await self.uuids.random_uuid_matrix((3, 3)) |
| 37 | + user_emoji = await self.emojis.random_emoji() |
| 38 | + ai_emoji = await self.emojis.random_emoji() |
| 39 | + player_order_random = await self.randoms.random() |
| 40 | + |
| 41 | + async with self.transaction: |
| 42 | + user = await self.users.user_with_id(location.user_id) |
| 43 | + |
| 44 | + if user is None: |
| 45 | + await self.user_views.render_user_is_not_registered_view( |
| 46 | + location, |
| 47 | + ) |
| 48 | + return |
| 49 | + |
| 50 | + try: |
| 51 | + tracking = Tracking() |
| 52 | + game = start_game_with_ai( |
| 53 | + cell_id_matrix, |
| 54 | + game_id, |
| 55 | + user, |
| 56 | + user_emoji, |
| 57 | + location.chat_id, |
| 58 | + ai_id, |
| 59 | + ai_type, |
| 60 | + ai_emoji, |
| 61 | + player_order_random, |
| 62 | + tracking, |
| 63 | + ) |
| 64 | + except UserAlreadyInGameError: |
| 65 | + await self.game_views.render_user_already_in_game_views( |
| 66 | + [location], |
| 67 | + ) |
| 68 | + else: |
| 69 | + await self.map_(tracking) |
| 70 | + await ( |
| 71 | + self.game_views |
| 72 | + .render_started_game_view_with_locations( |
| 73 | + [location.game(game.id)], game, |
| 74 | + ) |
| 75 | + ) |
0 commit comments