Ejemplo n.º 1
0
async def join_game(game_id: str, user: User = Depends(get_current_user)):
    """
    join an existing game. The user is injected as a dependency from the 
    required JWT cookie in the request. 
    """
    # ensure the game exists
    if game_id not in games:
        raise GAME_NOT_FOUND
    # ensure no user joins twice
    if user.uid in games[game_id].players:
        raise HTTPException(
            status_code=HTTP_400_BAD_REQUEST,
            detail=f"Player {user.username} has already joined.")
    # ensure only four players can join
    if len(games[game_id].players) >= games[game_id].n_players:
        raise HTTPException(
            status_code=HTTP_400_BAD_REQUEST,
            detail=f"The game is already full, there is no more room.")

    player = Player(**user.dict(), current_game=game_id)
    games[game_id].player_join(player)

    token = create_game_token(game_id)

    await sio_emit_game_list()

    return {'game_token': token}
Ejemplo n.º 2
0
async def initialize_new_game(player: User = Depends(get_current_user),
                              game_name: str = Body(...),
                              seed: int = None,
                              debug: bool = False):
    """
    Start a new game.
    """
    # check if the game_name is an empty string
    if not game_name:
        raise HTTPException(status_code=HTTP_400_BAD_REQUEST,
                            detail="Please enter a game name.")
    # check for duplicate name
    if game_name in [game.game_name for game in games.values()]:
        raise HTTPException(status_code=HTTP_400_BAD_REQUEST,
                            detail='A game with this name already exists.')

    game_id = ''.join(random.choice(string.ascii_uppercase) for i in range(4))
    while game_id in games:
        # generate new game ids until a new id is found
        game_id = ''.join(
            random.choice(string.ascii_uppercase) for i in range(4))

    games[game_id] = Brandi(game_id,
                            game_name=game_name,
                            host=player,
                            seed=seed,
                            debug=debug)

    await sio_emit_game_list()

    token = create_game_token(game_id)

    return {'game_token': token, 'game_id': game_id}