예제 #1
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
        }
예제 #2
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]
        }
예제 #3
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()
예제 #4
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}
예제 #5
0
def create_player(player_id):
    try:
        player = Player.get(player_id)
    except Player.DoesNotExist:
        logger.info("New player connecting, using defaults")
        player = Player(id=player_id)
    finally:
        return player
예제 #6
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!"}
예제 #7
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'
        }
예제 #8
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'}
    async def start(self, ctx, minutes_to_start : float = 30):
        game = Game.create(guild_id = ctx.guild.id)

        join_emoji = "⬆️"

        message = await game.log(f"React with an {join_emoji} to join. In {minutes_to_start} minutes the game will start.")
        await message.add_reaction(join_emoji)

        await asyncio.sleep(minutes_to_start * 60)

        message = await message.channel.fetch_message(message.id)

        join_reaction = None

        for reaction in message.reactions:
            if str(reaction.emoji) == join_emoji:
                join_reaction = reaction
                break

        members = [x for x in await join_reaction.users().flatten() if not x.bot]
        random.shuffle(members)


        if len(members) < 1:
            await message.edit(content = "Not enough players")
            game.delete_instance()
            return

        players = []
        for member in members:
            players.append(Player.create(user_id = member.id, game = game))

        game.start()
예제 #10
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"
        }
예제 #11
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
예제 #12
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")
예제 #13
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
예제 #14
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'}
예제 #15
0
파일: aws.py 프로젝트: carlos4ndre/xadrez
def get_authorizer_principal_id(event):
    if os.environ.get("IS_OFFLINE") == "true":
        connection_id = event["requestContext"].get("connectionId")
        for player in Player.scan():
            if player.connectionId == connection_id:
                return player.id
    return event["requestContext"]["authorizer"]["principalId"]
예제 #16
0
def create_players(players: list[str]) -> list[Player]:
    """Create list of player objects with
    assigned Trail Objects and Supplies."""

    player_list: list[Player] = []

    for i in enumerate(players):
        supply_options: list[str] = []
        trail_options: list[Trail] = []
        calamities: dict[str, str] = []
        for j in range(5):
            choic: str = choice(trails)
            trail = Trail(choic[0], choic[1], i[1], choic[2], choic[3],
                          choic[4])

            trail_options.append(trail)

            choi: str = choice(supplies)
            supply_options.append(choi)
        player_num: int = i[0] + 1
        player = Player(player_num, players[i[0]], supply_options,
                        trail_options, calamities)

        player_list.append(player)
    return player_list
예제 #17
0
def handler(event, context):
    connection_id = event["requestContext"].get("connectionId")
    logger.info("Create 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)
    challenger_id, challengee_id = data["challenger_id"], data["challengee_id"]
    game_options = data["game_options"]

    logger.info("Create game")
    game, err = create_game(challenger_id, challengee_id, game_options)
    if err:
        return create_aws_lambda_response(500, err)

    logger.info("Notify player")
    challenger = Player.get(challenger_id)
    content = {
        "challenger": {
            "id": challenger.id,
            "name": challenger.name,
            "nickname": challenger.nickname,
            "picture": challenger.picture,
        },
        "game": game.to_dict(),
    }
    err = notify_player(challengee_id, "createGame", content)
    if err:
        return create_aws_lambda_response(500, "Failed to notify player")
    return create_aws_lambda_response(200, "Create game successful")
예제 #18
0
def test_me_game():
    headers = {
        'Authorization': 'Bearer ' + pytest.users[1]["token"],
        'Content-Type': 'text/plain'
    }
    response = client.get(f"/games/{pytest.info['game']}/me", headers=headers)
    with db_session:
        player = Player.get(id=pytest.users[1]["player_id"])
        current_position = player.current_position
        role = player.role
        voldemort = player.is_voldemort
    assert response.status_code == 200
    assert response.json() == {
        "id": pytest.users[1]["player_id"],
        "choosable": True,
        "current_position": current_position,
        "role": role,
        "is_voldemort": voldemort,
        "alive": True,
        "user": pytest.users[1]["user_id"],
        "game": pytest.info['game']
    }
    response = client.get("/games/100/me", headers=headers)
    assert response.status_code == 404
    assert response.json() == {'detail': "The game does not exist"}
예제 #19
0
def get_player(player_id):
    try:
        player = Player.get(player_id)
        return player, ""
    except Exception as e:
        logger.error(e)
        return {}, "Failed to get player"
예제 #20
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'}
예제 #21
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)
    async def share(self, ctx, member : discord.Member):
        game = await self.choose_game(ctx.author)
        if game is None:
            return await ctx.send("No game running for you.")

        player = Player.get(game = game, user_id = ctx.author.id, alive = True)
        player_to_share_with = Player.get(game = game, user_id = member.id, alive = True)

        if player.id == player_to_share_with.id:
            return await ctx.send("Nice try.")

        player.cycle_immunity = True
        player.save()

        await member.send(f"{ctx.author} has shared their code with you. The code: {player.code}")

        await ctx.send("Okay. You are now immune to code leaks when this cycle ends.")
예제 #23
0
def notify_players(player_ids, action, content):
    try:
        data = {"action": action, "content": content}
        for player in Player.batch_get(player_ids,
                                       attributes_to_get=["connectionId"]):
            send_to_connection(player.connectionId, data)
    except Exception as e:
        logger.error(e)
        return "Failed to notify players"
예제 #24
0
async def expelliarmus(in_vote: VoteM, game_id: int, user=Depends(manager)):
    with db_session:
        game = Game.get(id=game_id)
        current_player = Player.user_player(user, game_id)
        username = User.get(id=current_player["user"]).username
        detail = f"The player {username} has played expelliarmus!"

        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 current_player["current_position"] != "minister" and current_player[
                "current_position"] != "headmaster":
            raise HTTPException(
                status_code=400,
                detail="this player is not the minister nor the headmaster")
        if game.board.de_proc < 5 or game.status["phase"] != "headmaster play":
            raise HTTPException(status_code=400,
                                detail="It is not time for expelliarmus!!!")

        if "headmaster_expelliarmus" not in game.status.keys():
            if current_player["current_position"] == 'headmaster':
                game.status["headmaster_expelliarmus"] = in_vote.vote
            else:
                raise HTTPException(
                    status_code=400,
                    detail="The headmaster must play the expelliarmus first!")
        else:
            if current_player["current_position"] == 'minister':
                game.status["minister_expelliarmus"] = in_vote.vote
            else:
                raise HTTPException(
                    status_code=400,
                    detail="The minister must confirm the expelliarmus!")
            detail = "The expelliarmus has failed!"
            if game.status["minister_expelliarmus"] and game.status[
                    "headmaster_expelliarmus"]:
                cards = game.board.deck.split(',')[2:]
                game.board.deck = ','.join(cards)
                detail = "the expelliarmus was played succesfully!, cards discarded"
                Player.reassign_minister(game)

        return {detail}
예제 #25
0
async def create_game(input_game: GameM, user=Depends(manager)):
    with db_session:
        new_game = Game(name=input_game.name,
                        created_by=user["id"],
                        started=False,
                        creation_date=datetime.datetime.now(),
                        player_amount=input_game.player_amount,
                        status={})
        new_player = Player(choosable=True,
                            current_position='',
                            role='',
                            is_voldemort=False,
                            alive=True,
                            user=User[user["id"]])
        new_game.players.add(new_player)
        new_player.game = new_game
        commit()
        status = {'id': new_game.id, 'message': 'Game created successfully'}
    return status
예제 #26
0
def get_players():
    try:
        players = []
        for player in Player.scan(attributes_to_get=GET_PLAYER_FIELDS,
                                  limit=MAX_RECORD_LIMIT):
            players.append(player.to_dict())
        return players, ""
    except Exception as e:
        logger.error(e)
        return {}, "Failed to get players"
예제 #27
0
async def kill_player(player_id: PlayerM, 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.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 game.status["phase"] != "spell play":
            raise HTTPException(status_code=400,
                                detail="Its not time for playing spells!")
        if not game.board.de_proc or deck[game.board.de_proc -
                                          1] != 'avadakedavra':
            raise HTTPException(
                status_code=400,
                detail="The avadakedavra spell is not available")
        if not victim_player:
            raise HTTPException(
                status_code=400,
                detail="The victim player does not belong to this game")
        if current_player["current_position"] != "minister":
            raise HTTPException(status_code=404,
                                detail="This player is not the minister")
        victim_player.alive = False
        if victim_player.is_voldemort:
            game.status = {
                "info": "game ended",
                "winner": "Phoenix Order",
                "detail": "voldemort killed"
            }
        else:
            Player.reassign_minister(game)
        victim_user = User.select(
            lambda u: u.id == victim_player.user.id).first()
        return {
            "avadakedavra": "succeed!",
            "dead_player_id": player_id.id,
            "dead_player_alias": victim_user.useralias
        }
예제 #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 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
예제 #30
0
    def test_player_factory(self):
        number = 1
        name = 'Miss Garbanzo'
        trail_options = [
            'Active Volcano to the Left',
            'Inactive Void of Once-Active Volcano to the Right'
        ]
        supplies = ['Vicodin', 'Revolver', 'Single Bullet', 'Garlic']
        calamities = ['Yellowstone explodes', 'Your gallstones explode']

        p: Player = Player.create(number, name, supplies, trail_options,
                                  calamities)

        self.assertEqual(number, p.number)
        self.assertEqual(name, p.name)
        for trail, supply in zip(trail_options, supplies):
            self.assertEqual(1, p.trail_options.get(trail))
            self.assertEqual(1, p.supplies.get(supply))