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()
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' }
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")
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")
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'}
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"}
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"
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.")
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
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 kill(self, ctx, code : str): 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) if not player.kill_command_available: return await ctx.send("You have already used your kill this cycle.") target = player.target if target.code == code: target.alive = False target.save() player.kills += 1 player.target = target.target player.save() if game.ended: await ctx.send(embed = discord.Embed(title = "🎯 Assassination successful.")) game.end() elif game.new_round_available: await ctx.send(embed = discord.Embed(title = "🎯 Assassination successful.")) game.next_round() else: await ctx.send(embed = discord.Embed(title = f"Assassination successful. 🎯 New target: {target.target.member}")) kill_message = KillMessage.get_random().value.format(user = target.member) await game.log(embed = discord.Embed(title = kill_message)) else: player.kill_command_available = False player.save() await ctx.send(embed = discord.Embed(title = "💩 You have failed to kill your target. You can try again when the next cycle starts."))
def test_vote_game(): headers = { 'Authorization': 'Bearer ' + pytest.users[1]["token"], 'Content-Type': 'text/plain' } response = client.post("/games/100/vote", headers=headers, json={"vote": "true"}) assert response.status_code == 404 assert response.json() == {'detail': "Game not found"} with db_session: game = Game.get(id=pytest.info['game']) game.status["phase"] = "x" response = client.post(f"/games/{pytest.info['game']}/vote", headers=headers, json={"vote": "true"}) assert response.status_code == 400 assert response.json() == {'detail': "It is not the vote phase"} with db_session: game = Game.get(id=pytest.info['game']) game.status["phase"] = "vote" response = client.post(f"/games/{pytest.info['game']}/vote", headers=headers, json={"vote": "true"}) assert response.status_code == 200 assert response.json() == { "vote": f"Player: {pytest.users[1]['player_id']} (andres) successfully voted", "election": "election in progress" } response = client.post(f"/games/{pytest.info['game']}/vote", headers=headers, json={"vote": "true"}) assert response.status_code == 400 assert response.json() == {"detail": "This player already voted"} votes = {0: "false", 1: "true"} for i in list(pytest.users.keys())[1:-2]: headers['Authorization'] = 'Bearer ' + pytest.users[i]["token"] response = client.post(f"/games/{pytest.info['game']}/vote", headers=headers, json={"vote": f"{votes[i%2]}"}) assert response.status_code == 200 assert response.json() == { "vote": f"Player: {pytest.users[i]['player_id']} ({pytest.users[i]['username']}) successfully voted", "election": "election in progress" } with db_session: old_status = Game.get(id=pytest.info['game']).status.copy() headers['Authorization'] = 'Bearer ' + pytest.users[5]["token"] Game.get(id=pytest.info['game']).status = old_status response = client.post(f"/games/{pytest.info['game']}/vote", headers=headers, json={"vote": "false"}) assert response.status_code == 200 assert response.json() == { "vote": f"Player: {pytest.users[5]['player_id']} ({pytest.users[5]['username']}) successfully voted", "election": "election failed" } game = Game.get(id=pytest.info['game']) game.board.caos -= 1 Player.get(id=game.status['minister']).current_position = "" game.status = old_status Player.get(id=old_status['minister']).current_position = "minister" Player.get( id=int(old_status['headmaster'])).current_position = "headmaster" response = client.post(f"/games/{pytest.info['game']}/vote", headers=headers, json={"vote": "true"}) assert response.status_code == 200 assert response.json() == { "vote": f"Player: {pytest.users[5]['player_id']} ({pytest.users[5]['username']}) successfully voted", "election": "election succeed" }
def test_choosehm_game(): with db_session: game = Game.get(id=pytest.info['game']) minister = game.status["minister"] game.status["phase"] = "x" headers = { 'Authorization': 'Bearer ' + pytest.users[1]["token"], 'Content-Type': 'text/plain' } response = client.post("/games/100/choosehm", headers=headers, json={'id': '2'}) assert response.status_code == 404 assert response.json() == {'detail': "Game not found"} response = client.post(f"/games/{pytest.info['game']}/choosehm", headers=headers, json={'id': '2'}) assert response.status_code == 400 assert response.json() == { 'detail': "The headmaster only can be elected in the propose phase" } with db_session: game = Game.get(id=pytest.info['game']) game.status["phase"] = "propose" for i in pytest.users.keys(): if pytest.users[i]["player_id"] != minister: acc = i break headers['Authorization'] = 'Bearer ' + pytest.users[acc]["token"] response = client.post(f"/games/{pytest.info['game']}/choosehm", headers=headers, json={'id': '2'}) assert response.status_code == 400 assert response.json() == { 'detail': "Only the minister can propose a headmaster" } 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.post(f"/games/{pytest.info['game']}/choosehm", headers=headers, json={"id": "300"}) assert response.status_code == 400 assert response.json() == {'detail': "The selected player does not exist"} response = client.post(f"/games/{pytest.info['game']}/choosehm", headers=headers, json={"id": str(minister)}) assert response.status_code == 400 assert response.json() == { 'detail': "The minister can not be the headmaster" } with db_session: other_guy = Player.get(id=pytest.users[acc]["player_id"]) other_guy.choosable = False response = client.post(f"/games/{pytest.info['game']}/choosehm", headers=headers, json={"id": str(pytest.users[acc]["player_id"])}) assert response.status_code == 400 assert response.json() == { 'detail': "The player has been headmaster in the previous round" } with db_session: user = User.get(id=pytest.users[user_minister]["user_id"]) new_game = Game(name="x", created_by=pytest.users[acc]["user_id"], started=False, creation_date=datetime.datetime.now(), player_amount=5, status={}) new_player = Player(choosable=True, current_position='', role='', is_voldemort=False, alive=True, user=user) new_game.players.add(new_player) other_guy = Player.get(id=pytest.users[acc]["player_id"]) other_guy.choosable = True other_guy.alive = False commit() pytest.info['other_game'] = new_game.id pytest.info['other_player'] = new_player.id response = client.post(f"/games/{pytest.info['game']}/choosehm", headers=headers, json={"id": str(new_player.id)}) assert response.status_code == 400 assert response.json() == { 'detail': "The player does not belong to this game" } response = client.post(f"/games/{pytest.info['game']}/choosehm", headers=headers, json={"id": str(other_guy.id)}) assert response.status_code == 400 assert response.json() == { 'detail': "The player cannot be headmaster because is dead" } with db_session: other_guy = Player.get(id=pytest.users[acc]["player_id"]) other_guy.alive = True username = other_guy.user.username response = client.post(f"/games/{pytest.info['game']}/choosehm", headers=headers, json={"id": str(other_guy.id)}) assert response.status_code == 200 assert response.json() == { "message": f"The player number {other_guy.id}: {username} was proposed as headmaster" }
async def vote(in_vote: VoteM, 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.status["phase"] != "vote": raise HTTPException(status_code=400, detail="It is not the vote phase") current_player = Player.user_player(user, game_id) vote_arr = [{ "player": current_player["id"], "user": user["id"], "username": user["username"], "vote": in_vote.vote }] if 'votes' in game.status.keys(): for v in game.status["votes"]: if v["user"] == user["id"]: raise HTTPException(status_code=400, detail="This player already voted") game.status["votes"] = game.status["votes"] + vote_arr else: game.status["votes"] = vote_arr pid = current_player["id"] username = user["username"] player_msg = f"Player: {pid} ({username}) successfully voted" general_msg = "election in progress" if len(game.status["votes"]) == game.players.select( lambda p: p.alive).count(): nox_votes = 0 lumos_votes = 0 for v in game.status["votes"]: if v["vote"]: lumos_votes += 1 else: nox_votes += 1 if lumos_votes > nox_votes: # PASS THE TURN ###################### game.board.caos = 0 game.status["phase"] = "minister play" general_msg = "election succeed" new_hm = Player.get(id=game.status["headmaster"]) if new_hm and (game.player_amount == 5 or game.player_amount == 6) \ and game.board.de_proc > 3 and new_hm.is_voldemort: game.status = { "info": "game ended", "winner": "Death Eaters", "detail": "voldemort headmaster" } return {"vote": player_msg, "election": general_msg} ###################################### else: # PASS THE TURN ##################### game.board.caos = game.board.caos + 1 general_msg = "election failed" # ACTIONS TO DO IF CAOS IS EQUAL TO 3 if game.board.caos == 3: deck = game.board.deck.split(',') first_card = deck[:1] if first_card[0] == 'death': game.board.de_proc += 1 else: game.board.po_proc += 1 if 'caos' in game.status.keys(): game.status["caos"] = game.status["caos"] + first_card else: game.status["caos"] = first_card game.board.deck = ','.join(deck[1:]) game.board.caos = 0 general_msg = "government caos" Player.reset_choosable() ##################################### Player.reassign_minister(game) return {"vote": player_msg, "election": general_msg}