Пример #1
0
def test_delete_game():
    headers = {
        'Authorization': 'Bearer ' + pytest.users[2]["token"],
        'Content-Type': 'text/plain'
    }
    response = client.delete("/games/100/delete", headers=headers)
    assert response.status_code == 404
    assert response.json() == {'detail': 'The game does not exist'}
    response = client.delete(f"/games/{pytest.info['game']}/delete",
                             headers=headers)
    assert response.status_code == 403
    assert response.json() == {
        'detail': 'The game does not belong to the current user'
    }
    headers['Authorization'] = 'Bearer ' + pytest.users[1]["token"]
    response = client.delete(f"/games/{pytest.info['game']}/delete",
                             headers=headers)
    assert response.status_code == 200
    assert response.json() == {
        "message": f"The game {pytest.info['game']} (Partida 1) was deleted"
    }
    with db_session:
        Player.get(id=pytest.info['other_player']).delete()
        Game.get(id=pytest.info['other_game']).delete()
        for u in list(pytest.users.values())[:-1]:
            User.get(id=u["user_id"]).delete()
Пример #2
0
async def get_status(game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        status = game.status.copy()
        return status
Пример #3
0
async def get_specific_game(game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        result = game.to_dict()
    return result
Пример #4
0
def handler(event, context):
    connection_id = event["requestContext"].get("connectionId")
    logger.info("Leave game request from connectionId {})".format(connection_id))

    logger.info("Parse event")
    data, err = parse_event(event)
    if err:
        return create_aws_lambda_response(500, err)
    game_id, player_id = data["game_id"], data["player_id"]
    game = Game.get(game_id)

    logger.info("Check player permissions")
    if not game.is_player_in_game(player_id):
        return create_aws_lambda_response(403, "Player is not part of the game")

    logger.info("Resign player")
    err = resign_player(game, player_id)
    if err:
        return create_aws_lambda_response(500, err)

    logger.info("Notify players")
    player_ids = [game.whitePlayerId, game.blackPlayerId]
    err = notify_players(player_ids, "endGame", {"game": game.to_dict()})
    if err:
        return create_aws_lambda_response(500, err)
    return create_aws_lambda_response(200, "Leave game successful")
Пример #5
0
async def get_proclamations(game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)

        current_player = Player.user_player(user, game_id)

        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if game.status["phase"] == "minister play":
            if current_player["current_position"] != "minister":
                raise HTTPException(status_code=404,
                                    detail="This player is not the minister")
            cards = game.board.deck.split(',')[:3]
            data = {"data": cards}
        elif game.status["phase"] == "headmaster play":
            if current_player["current_position"] != "headmaster":
                raise HTTPException(status_code=404,
                                    detail="This player is not the headmaster")
            cards = game.board.deck.split(',')[:2]
            data = {"data": cards}
        else:
            raise HTTPException(
                status_code=400,
                detail="It is not a phase for geting a proclamation")
        return data
Пример #6
0
async def play(proc: ProcM, game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")

        current_player = Player.user_player(user, game_id)

        if game.status["phase"] == "minister play":
            if current_player["current_position"] != "minister":
                raise HTTPException(status_code=404,
                                    detail="This player is not the minister")
            cards = game.board.deck.split(',')[:3]
            if proc.card in cards:
                cards = game.board.deck.split(',')
                cards.remove(proc.card)
                game.board.deck = ','.join(cards)
            else:
                raise HTTPException(
                    status_code=400,
                    detail="The input card was not one of the options")
            msg = f'{proc.card} card discarded successfully'
            # PASS THE TURN #####################
            game.status["phase"] = "headmaster play"
            #####################################

        elif game.status["phase"] == "headmaster play":
            if current_player["current_position"] != "headmaster":
                raise HTTPException(status_code=404,
                                    detail="This player is not the headmaster")
            cards = game.board.deck.split(',')[:2]
            if proc.card in cards:
                cards = game.board.deck.split(',')[2:]
                game.board.deck = ','.join(cards)
                if proc.card == 'phoenix':
                    game.board.po_proc += 1
                else:
                    game.board.de_proc += 1
                # IMPORTANT! HERE GOES THE LOGIC FOR SPELL ACTIVATION
                # PASS THE TURN ###########
                spell_fields = game.board.spell_fields.split(",")
                spells = ["divination", "avadakedavra", "imperius", "crucio"]
                if game.board.de_proc != 0 and spell_fields[game.board.de_proc
                                                            - 1] in spells:
                    game.status["phase"] = "spell play"
                else:
                    Player.reassign_minister(game)
                #####################################
                msg = f'{proc.card} card played successfully'
            else:
                raise HTTPException(
                    status_code=400,
                    detail="The input card was not one of the options")

        else:
            raise HTTPException(
                status_code=400,
                detail="It is not a phase for playing a proclamation")

        return {"message": msg}
Пример #7
0
def handler(event, context):
    connection_id = event["requestContext"].get("connectionId")
    logger.info("Send message request from connectionId {})".format(connection_id))

    logger.info("Parse event")
    data, err = parse_event(event)
    if err:
        return create_aws_lambda_response(500, err)
    game_id, player_id, text = data["game_id"], data["player_id"], data["text"]
    game = Game.get(game_id)

    logger.info("Check player permissions")
    if not game.is_player_in_game(player_id):
        return create_aws_lambda_response(403, "Player is not part of the game")

    logger.info("Generate message")
    sender = Player.get(player_id)
    message = generate_message(game.id, sender, text)

    logger.info("Save message")
    _, err = create_message(game_id, player_id, message["text"])
    if err:
        return create_aws_lambda_response(500, err)

    logger.info("Send message to players")
    player_ids = [game.whitePlayerId, game.blackPlayerId]
    err = notify_players(player_ids, "sendMessage", {"message": message})
    if err:
        return create_aws_lambda_response(500, err)
    return create_aws_lambda_response(200, "Send message successful")
Пример #8
0
async def all_messages(game_id: int, user=Depends(manager)):
    with db_session:

        def user_data(obj_player):
            c_user = obj_player.user
            return {
                "id": c_user.id,
                "username": c_user.username,
                "useralias": c_user.useralias
            }

        game = Game.get(id=game_id)
        Player.user_player(user, game_id)
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if not game.started:
            raise HTTPException(status_code=400, detail="Game is not started")
        chats = game.chats.order_by(lambda c: desc(c.date))
        return {
            'data': [{
                "content": m.content,
                "date": m.date,
                "send_by": user_data(m.player)
            } for m in chats]
        }
Пример #9
0
def test_post_msg():
    headers = {
        'Authorization': 'Bearer ' + pytest.users[2]["token"],
        'Content-Type': 'text/plain'
    }
    response = client.post(f"/games/{pytest.info['game']}/messages",
                           headers=headers,
                           json={"content": "Hola Guachin"})
    assert response.status_code == 200
    assert response.json() == {
        "detail": "the message was recorder successfully"
    }
    response = client.post(f"/games/1000/messages",
                           headers=headers,
                           json={"content": "Hola Guachin"})
    assert response.status_code == 404
    assert response.json() == {'detail': 'Game not found'}
    with db_session:
        game = Game.get(id=pytest.info['game'])
        game.started = False
        response = client.post(f"/games/{pytest.info['game']}/messages",
                               headers=headers,
                               json={"content": "Hola Guachin"})
        assert response.status_code == 400
        assert response.json() == {'detail': "Game is not started"}
        game.started = True
Пример #10
0
def test_board_game():
    headers = {
        'Authorization': 'Bearer ' + pytest.users[1]["token"],
        'Content-Type': 'text/plain'
    }
    response = client.get(f"/games/{pytest.info['game']}/board",
                          headers=headers)
    with db_session:
        current_position = Player.get(
            id=pytest.users[1]["player_id"]).current_position
        game = Game.get(id=pytest.info['game'])
        board = game.board.id
        minister = int(game.status["minister"])
    assert response.status_code == 200
    assert response.json() == {
        "id":
        board,
        "de_proc":
        0,
        "po_proc":
        0,
        "spell_fields":
        ["", "", "divination", "avadakedavra", "avadakedavra", "win"],
        "caos":
        0,
        "game":
        pytest.info['game']
    }
    response = client.get("/games/100/board", headers=headers)
    assert response.status_code == 404
    assert response.json() == {'detail': 'Game not found'}
Пример #11
0
def test_get_msg():
    headers = {
        'Authorization': 'Bearer ' + pytest.users[3]["token"],
        'Content-Type': 'text/plain'
    }
    with db_session:
        date = str(
            Message.select(
                lambda u: u.game.id == pytest.info['game']).first().date)
        date = date.replace(" ", "T")
    response = client.get(f"/games/{pytest.info['game']}/messages",
                          headers=headers)
    assert response.status_code == 200
    assert response.json() == {
        "data": [{
            "content": "Hola Guachin",
            "date": date,
            "send_by": {
                "id": pytest.users[2]["user_id"],
                "username": "******",
                "useralias": "andres2"
            }
        }]
    }
    with db_session:
        game = Game.get(id=pytest.info['game'])
        game.started = False
        response = client.get(f"/games/{pytest.info['game']}/messages",
                              headers=headers)
        assert response.status_code == 400
        assert response.json() == {'detail': "Game is not started"}
        game.started = True
Пример #12
0
def handler(event, context):
    connection_id = event["requestContext"].get("connectionId")
    logger.info(
        "Reject game request from connectionId {})".format(connection_id))

    logger.info("Parse event")
    data, err = parse_event(event)
    if err:
        return create_aws_lambda_response(500, err)
    game_id, challengee_id = data["game_id"], data["challengee_id"]
    game = Game.get(game_id)

    logger.info("Check player permissions")
    if not game.is_player_in_game(challengee_id):
        return create_aws_lambda_response(403,
                                          "Player is not part of the game")

    logger.info("Reject game")
    err = reject_game(game, challengee_id)
    if err:
        return create_aws_lambda_response(500, err)

    logger.info("Notify player")
    challenger_id = game.get_opponent_id(challengee_id)
    err = notify_player(challenger_id, "endGame", {"game": game.to_dict()})
    if err:
        return create_aws_lambda_response(500, err)
    return create_aws_lambda_response(200, "Reject game successful")
Пример #13
0
def test_get_game():
    headers = {
        'Authorization': 'Bearer ' + pytest.users[2]["token"],
        'Content-Type': 'text/plain'
    }
    response = client.get(f"/games/{pytest.info['game']}", headers=headers)
    with db_session:
        game = Game.get(id=pytest.info['game'])
        creation_date = str(game.creation_date).replace(" ", "T")
        minister = int(game.status["minister"])
        created_by = int(game.created_by)
        board = game.board.id
    assert response.status_code == 200
    assert response.json() == {
        "id": pytest.info['game'],
        "name": "Partida 1",
        "creation_date": creation_date,
        "created_by": created_by,
        "player_amount": 5,
        "started": True,
        "status": {
            "minister": minister,
            "phase": "propose",
            "round": 1
        },
        "board": board
    }
    response = client.get("/games/100", headers=headers)
    assert response.status_code == 404
    assert response.json() == {'detail': 'Game not found'}
Пример #14
0
def test_post_avadakedavra():
    with db_session:
        game = Game.get(id=pytest.info['game'])
        player = Player.select(lambda p: p.current_position == "" and p.game.id
                               == game.id).first()
        for i in pytest.users.keys():
            if pytest.users[i]["user_id"] == player.user.id:
                user = i
                break
        headers = {
            'Authorization': 'Bearer ' + pytest.users[user]["token"],
            'Content-Type': 'text/plain'
        }
        response = client.post(f"/games/{pytest.info['game']}/avadakedavra",
                               headers=headers,
                               json={'id': pytest.users[2]["player_id"]})
        assert response.status_code == 400
        assert response.json() == {
            "detail": "Its not time for playing spells!"
        }
        game.status["phase"] = "spell play"
        response = client.post(f"/games/{pytest.info['game']}/avadakedavra",
                               headers=headers,
                               json={'id': pytest.users[2]["player_id"]})
        assert response.status_code == 400
        assert response.json() == {
            "detail": "The avadakedavra spell is not available"
        }
Пример #15
0
def test_get_crucio():
    with db_session:
        game = Game.get(id=pytest.info['game'])
        player = Player.select(lambda p: p.current_position == "" and p.game.id
                               == game.id).first()
        for i in pytest.users.keys():
            if pytest.users[i]["user_id"] == player.user.id:
                user = i
                break
        headers = {
            'Authorization': 'Bearer ' + pytest.users[user]["token"],
            'Content-Type': 'text/plain'
        }
        game.status["phase"] = "otro estado"
        response = client.get(f"/games/{pytest.info['game']}/crucio/4000",
                              headers=headers)
        assert response.status_code == 400
        assert response.json() == {
            "detail": "The victim player does not belong to this game"
        }
        response = client.get(
            f"/games/{pytest.info['game']}/crucio/{pytest.users[user]['player_id']}",
            headers=headers)
        assert response.status_code == 400
        assert response.json() == {
            "detail": "Its not time for playing spells!"
        }
        game.status["phase"] = "spell play"
        game.started = False
        response = client.get(f"/games/{pytest.info['game']}/divination",
                              headers=headers)
        assert response.status_code == 400
        assert response.json() == {"detail": "Game is not started"}
        game.started = True
Пример #16
0
async def play_crucio(player_id: int, game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        current_player = Player.user_player(user, game_id)
        victim_player = Player.select(
            lambda p: p.id == player_id and p.game.id == game_id).first()
        deck = game.board.spell_fields.split(",")
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if not game.started:
            raise HTTPException(status_code=400, detail="Game is not started")
        if not victim_player:
            raise HTTPException(
                status_code=400,
                detail="The victim player does not belong to this game")
        if game.status["phase"] != "spell play":
            raise HTTPException(status_code=400,
                                detail="Its not time for playing spells!")
        if current_player["current_position"] != "minister":
            raise HTTPException(status_code=400,
                                detail=f"This player is not the minister")
        if game.board.de_proc == 0 or deck[game.board.de_proc - 1] != "crucio":
            raise HTTPException(status_code=400,
                                detail="The crucio spell is not available")
        victim_user = User.select(
            lambda u: u.id == victim_player.user.id).first()
        role = victim_player.role
        return {
            "role": role,
            "player_id": player_id,
            "player_alias": victim_user.useralias
        }
Пример #17
0
async def get_deck(game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if not game.started:
            raise HTTPException(status_code=400, detail="Game is not started")
        return game.board.deck
Пример #18
0
async def get_current_player(game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        if game is None:
            raise HTTPException(status_code=404,
                                detail="The game does not exist")

        return Player.user_player(user, game_id)
Пример #19
0
def test_get_divination():
    with db_session:
        headers = {
            'Authorization': 'Bearer ' + pytest.users[1]["token"],
            'Content-Type': 'text/plain'
        }
        #response = client.get("/games/100/divination", headers=headers)
        game = Game.get(id=pytest.info['game'])
        game.status["minister"]
Пример #20
0
async def end_turn(game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if not game.started:
            raise HTTPException(status_code=400, detail="Game is not started")
        Player.reassign_minister(game)
        return {"message": "Turn ended!"}
Пример #21
0
def handler(event, context):
    connection_id = event["requestContext"].get("connectionId")
    logger.info(
        "Move piece request from connectionId {})".format(connection_id))

    logger.info("Parse event")
    data, err = parse_event(event)
    if err:
        return create_aws_lambda_response(500, err)
    game_id, player_id, move_san = data["game_id"], data["player_id"], data[
        "move_san"]
    game = Game.get(game_id)

    logger.info("Check player permissions")
    if not game.is_player_in_game(player_id):
        return create_aws_lambda_response(403,
                                          "Player is not part of the game")
    if not game.is_player_turn(player_id):
        return create_aws_lambda_response(403, "It is not player turn to play")

    logger.info("Check move is valid")
    game.moves.append(move_san)
    board = generate_board_from_moves(game.moves)
    if not board.is_valid():
        notify_player(player_id, "movePieceFailure",
                      {"error": str(board.status())})
        return create_aws_lambda_response(400, "Invalid move")

    status, result = is_game_ended(game, board)
    if status:
        logger.info("Update game with the final result")
        err = end_game(game, status, result)
        if err:
            return create_aws_lambda_response(500, err)

        logger.info("Notify players the game has ended")
        player_ids = [game.whitePlayerId, game.blackPlayerId]
        err = notify_players(player_ids, "endGame", {"game": game.to_dict()})
        if err:
            return create_aws_lambda_response(500, err)
        return create_aws_lambda_response(200, "End game successful")

    logger.info("Move piece")
    err = move_piece(game, board.fen())
    if err:
        return create_aws_lambda_response(500, err)

    logger.info("Notify users the move is valid")
    player_ids = [game.whitePlayerId, game.blackPlayerId]
    err = notify_players(player_ids, "movePieceSuccess",
                         {"game": game.to_dict()})
    if err:
        return create_aws_lambda_response(500, "Failed to notify players")

    return create_aws_lambda_response(200, "Move piece successful")
Пример #22
0
async def get_board(game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if not game.started:
            raise HTTPException(status_code=400, detail="Game is not started")
        board = game.board.to_dict().copy()
        spell_fields = board["spell_fields"]
        board["spell_fields"] = spell_fields.split(",")
        return board
Пример #23
0
def test_get_proclamations_game():
    with db_session:
        game = Game.get(id=pytest.info["game"])
        minister = game.status['minister']
        headmaster = int(game.status['headmaster'])
        for i in pytest.users.keys():
            if pytest.users[i]["player_id"] != minister and pytest.users[i][
                    "player_id"] != headmaster:
                acc = i
                break
        headers = {
            'Authorization': 'Bearer ' + pytest.users[acc]["token"],
            'Content-Type': 'text/plain'
        }
        game.status["phase"] = "x"
        response = client.get(f"/games/{pytest.info['game']}/proclamations",
                              headers=headers)
        assert response.status_code == 400
        assert response.json() == {
            'detail': "It is not a phase for geting a proclamation"
        }
        game.status["phase"] = "minister play"
        response = client.get(f"/games/{pytest.info['game']}/proclamations",
                              headers=headers)
        assert response.status_code == 404
        assert response.json() == {'detail': "This player is not the minister"}
        for i in pytest.users.keys():
            if pytest.users[i]["player_id"] == minister:
                user_minister = i
                break
        headers[
            'Authorization'] = 'Bearer ' + pytest.users[user_minister]["token"]
        response = client.get(f"/games/{pytest.info['game']}/proclamations",
                              headers=headers)
        assert response.status_code == 200
        assert response.json() == {"data": game.board.deck.split(',')[:3]}
        game.status["phase"] = "headmaster play"
        response = client.get(f"/games/{pytest.info['game']}/proclamations",
                              headers=headers)
        assert response.status_code == 404
        assert response.json() == {
            'detail': "This player is not the headmaster"
        }
        for i in pytest.users.keys():
            if pytest.users[i]["player_id"] == headmaster:
                user_headmaster = i
                break
        headers['Authorization'] = 'Bearer ' + pytest.users[user_headmaster][
            "token"]
        response = client.get(f"/games/{pytest.info['game']}/proclamations",
                              headers=headers)
        assert response.status_code == 200
        assert response.json() == {"data": game.board.deck.split(',')[:2]}
Пример #24
0
async def choose_headmaster(headmaster: PlayerM,
                            game_id: int,
                            user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if not game.started:
            raise HTTPException(status_code=400, detail="Game is not started")
        status = game.status
        player = Player.get(id=status["minister"])
        if status["phase"] != "propose":
            raise HTTPException(
                status_code=400,
                detail="The headmaster only can be elected in the propose phase"
            )
        if player.user.id != user["id"]:
            raise HTTPException(
                status_code=400,
                detail="Only the minister can propose a headmaster")
        new_hm = Player.get(id=headmaster.id)
        if new_hm is None:
            raise HTTPException(status_code=400,
                                detail="The selected player does not exist")
        if new_hm.id == status["minister"]:
            raise HTTPException(
                status_code=400,
                detail="The minister can not be the headmaster")
        if not new_hm.choosable:
            raise HTTPException(
                status_code=400,
                detail="The player has been headmaster in the previous round")
        if new_hm.game.id != game_id:
            raise HTTPException(
                status_code=400,
                detail="The player does not belong to this game")
        if not new_hm.alive:
            raise HTTPException(
                status_code=400,
                detail="The player cannot be headmaster because is dead")
        Player.reset_choosable()
        status["headmaster"] = int(headmaster.id)
        # PASS THE TURN ####################
        status["phase"] = "vote"
        #####################################
        game.status = status
        new_hm.current_position = "headmaster"
        new_hm.choosable = False
        return {
            "message":
            f'The player number {new_hm.id}: {new_hm.user.username} was proposed as headmaster'
        }
Пример #25
0
async def left_game(game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if game.started:
            raise HTTPException(status_code=400,
                                detail="The Game is already started")

        current_player = Player.user_player(user, game_id)
        player_obj = Player.get(id=current_player["id"])
        player_obj.delete()

    return {"message": 'game left successfully'}
Пример #26
0
def test_deck_game():
    headers = {
        'Authorization': 'Bearer ' + pytest.users[1]["token"],
        'Content-Type': 'text/plain'
    }
    with db_session:
        deck = Game.get(id=pytest.info['game']).board.deck
    response = client.get(f"/games/{pytest.info['game']}/deck",
                          headers=headers)
    assert response.status_code == 200
    assert response.json() == deck
    response = client.get("/games/100/deck", headers=headers)
    assert response.status_code == 404
    assert response.json() == {'detail': "Game not found"}
Пример #27
0
async def list_players(game_id: int, user=Depends(manager)):
    status = {}
    with db_session:
        game = Game.get(id=game_id)
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        players = game.players
        parsed_players = [p.to_dict() for p in players]
        parsed_players.sort(key=lambda x: x.get('id'))
        for p in parsed_players:
            user = User.get(id=p['user']).to_dict()
            user.pop("password")
            user.pop("email")
            p.update(user=user)
    return {'data': parsed_players}
Пример #28
0
async def write_message(msg_content: MessageM,
                        game_id: int,
                        user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        current_player = Player.select(lambda p: user["id"] == p.user.id and p.
                                       game.id == game_id).first()
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if not game.started:
            raise HTTPException(status_code=400, detail="Game is not started")
        Message(date=datetime.datetime.now(),
                content=msg_content.content,
                game=game_id,
                player=current_player)
        return {"detail": "the message was recorder successfully"}
Пример #29
0
async def join_game(game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        if game is None:
            raise HTTPException(status_code=404, detail="Game not found")
        if game.players.count() == game.player_amount:
            raise HTTPException(status_code=403, detail="The game is full")
        new_player = Player(choosable=True,
                            current_position='',
                            role='',
                            is_voldemort=False,
                            alive=True,
                            user=User[user["id"]])
        new_player.game = game
        game.players.add(new_player)
    return {"message": 'joined successfully'}
Пример #30
0
async def start_game(game_id: int, user=Depends(manager)):
    status = {}
    with db_session:
        current_game = Game.get(id=game_id)
        # IMPORTANT!!!:
        # Currently this is not checking that the game is full before continue (for testing purposes)

        if current_game is None:
            raise HTTPException(status_code=404,
                                detail="The game does not exist")
        if current_game.started:
            raise HTTPException(status_code=400,
                                detail="The game was already started")
        if current_game.created_by != user["id"]:
            raise HTTPException(
                status_code=403,
                detail="The game does not belong to the current user")

        # spell board and random deck
        spell_fields = ','.join(Board.define_board(current_game.player_amount))
        random_deck = ','.join(Board.new_deck(50))

        new_board = Board(de_proc=0,
                          po_proc=0,
                          spell_fields=spell_fields,
                          caos=0,
                          game=current_game,
                          deck=random_deck)
        current_game.started = True
        current_game.board = new_board

        # Role choosing
        role_info = Player.assign_roles(current_game.players)

        current_game.status = {
            "round": 1,
            "phase": 'propose',
            "minister": role_info,
        }

        commit()

        status = {
            'board_id': new_board.id,
            'message': 'Game started successfully'
        }
    return status