コード例 #1
0
def test_advance_pointThresholdReached_gameEnds(started_game: Game, winner):
    winner = started_game.players[winner % started_game.num_players]
    started_game.points[winner] = started_game.points_threshold
    force_end_round(started_game.current_round)
    end = started_game.advance()
    assert end.type == GameState.Type.END
    assert end.winner is winner
コード例 #2
0
    def compare_agents(lambda_01, lambda_02, games_to_play=51, seed=451):
        """
        Returns number of times agent created from lambda_01
        wins over agent created from lambda_02 (which plays all the other
        positions)
        """
        wins = 0

        if lambda_01 is lambda_02:
            # Playing against yourself is nonsensical
            return 0

        for idx in range(games_to_play):
            game = Game.new(4, seed + idx)
            agent_one = (lambda_01)(seed + idx)
            agent_two = (lambda_02)(seed + idx)

            while game.active():
                if not game.is_current_player_playing():
                    game = game.skip_eliminated_player()
                    continue

                if game.player_turn() == 0:
                    action = agent_one.move(game)
                else:
                    action = agent_two.move(game)
                game, _ = game.move(action)

            if game.is_winner(0):
                wins = wins + 1
        print('%s won against %s %.1f%% of games' %
              (agent_one, agent_two, wins * 100 / games_to_play))
        return wins
コード例 #3
0
def test_eventGenerator_yieldsCorrectTypes(new_game: Game):
    def is_game_start(e: GameEvent):
        return isinstance(e, GameState) and e.type == GameState.Type.ROUND

    def is_round_end(e: GameEvent):
        return isinstance(
            e, GameNodeState) and e.type == RoundState.Type.ROUND_END

    game_generator = new_game.play()
    event = next(game_generator)
    # all input requests until the round starts
    while not is_game_start(event):
        assert isinstance(event, GameInputRequest)
        event = game_generator.send(autofill_step(event))

    # until the round ends, repeat: round -> player move choice -> move steps -> results
    while True:
        # starts with round event
        assert isinstance(event, loveletter.game.PlayingRound)

        # now all of the round events
        event = next(game_generator)
        while not is_round_end(event):
            event = game_generator.send(autofill_step(event))

        # advance (perhaps finish the game)
        try:
            event = next(game_generator)
        except StopIteration as e:
            results = e.value
            break

    assert tuple(r.type for r in results) == (GameNodeState.Type.END, )
コード例 #4
0
ファイル: test_games.py プロジェクト: user01/love-letter
    def test_end_elimination(self):
        """Reach the end of a game by elimination"""
        game = Game.new(4, 0)

        game, _ = game.move(
            PlayerAction(Card.guard, 1, Card.priest, Card.noCard))
        game = game.skip_eliminated_player()
        game, _ = game.move(
            PlayerAction(Card.guard, 3, Card.countess, Card.noCard))
        game, _ = game.move(
            PlayerAction(Card.handmaid, 3, Card.noCard, Card.noCard))

        game, _ = game.move(
            PlayerAction(Card.countess, 0, Card.noCard, Card.noCard))
        game = game.skip_eliminated_player()
        game, _ = game.move(
            PlayerAction(Card.baron, 3, Card.noCard, Card.noCard))
        game, _ = game.move(
            PlayerAction(Card.guard, 2, Card.handmaid, Card.noCard))

        self.assertFalse(game.over())
        game, _ = game.move(
            PlayerAction(Card.princess, 0, Card.noCard, Card.noCard))

        self.assertEqual(game.cards_left(), 4)
        self.assertTrue(game.over())
コード例 #5
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_move_handmaid(self):
        """Deploy the handmaid and survive attack"""
        game = Game.new(4, 2)
        action = PlayerAction(Card.handmaid, 0, Card.noCard, Card.noCard)
        game, _ = game.move(action)

        players = game.players()
        player = players[0]
        self.assertTrue(PlayerTools.is_playing(player))
        self.assertFalse(PlayerActionTools.is_blank(player.actions[0]))
        self.assertEqual(player.actions[0], action)
        for action in player.actions[1:]:
            self.assertTrue(PlayerActionTools.is_blank(action))

        action_attack = PlayerAction(Card.guard, 0, Card.prince, Card.noCard)
        game, _ = game.move(action_attack)

        players = game.players()
        target = players[0]
        player = players[1]
        self.assertTrue(PlayerTools.is_playing(player))
        self.assertTrue(PlayerTools.is_playing(target))

        self.assertFalse(PlayerActionTools.is_blank(player.actions[0]))
        self.assertEqual(player.actions[0], action_attack)
        for action in player.actions[1:]:
            self.assertTrue(PlayerActionTools.is_blank(action))

        for action in target.actions[1:]:
            self.assertTrue(PlayerActionTools.is_blank(action))
コード例 #6
0
ファイル: play.py プロジェクト: adamschmideg/love-letter
def play_with_agents(seed, *agents):
    all_players = [None, AgentRandom()]
    game = Game.new(len(all_players), seed)
    actions = []
    while game.active():
        if not game.is_current_player_playing():
            game = game.skip_eliminated_player()
            continue

        display(game, actions)

        current_player = all_players[game.player_turn()]

        if current_player:
            action = current_player.move(game)
            actions.append(action)
            game, _ = game.move(action)
        else:
            try:
                print("  What card to play?")
                action = get_action()
                actions.append(action)
                game, _ = game.move(action)
            except ValueError:
                print("Invalid move - Exit with Ctrl-C")

    display(game, actions)
    print("Game Over : Player {} Wins!".format(game.winner()))
コード例 #7
0
def test_start_newGame_setsCorrectGameState(new_game: Game):
    new_game.start()
    assert new_game.started
    assert not new_game.ended
    assert new_game.state.type == GameState.Type.ROUND

    # noinspection PyTypeChecker
    state: loveletter.game.PlayingRound = new_game.state
    assert state.round_no == 1
    assert state.first_player is None

    assert new_game.current_round is state.round
    game_round = new_game.current_round
    assert isinstance(game_round, Round)
    assert not game_round.started
    assert game_round.num_players == new_game.num_players
コード例 #8
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_move_guard_success(self):
        """Getting a guard move, with a right guess"""
        game = Game.new()
        action = PlayerAction(Card.guard, 3, Card.handmaid, 0)
        self.assertEqual(len(game.opponents()), 3)
        self.assertListEqual(game.opponent_turn(), [1, 2, 3])
        game, _ = game.move(action)

        self.assertEqual(game.round(), 0)
        self.assertEqual(game.player_turn(), 1)
        self.assertEqual(game.cards_left(), 10)
        self.assertTrue(game.active())
        self.assertFalse(game.over())

        players = game.players()
        player = players[0]
        target = players[3]
        recent_action = player.actions[0]
        self.assertListEqual(game.opponent_turn(), [0, 2])
        self.assertEqual(len(game.opponents()), 2)

        self.assertFalse(PlayerTools.is_playing(target))
        self.assertEqual(recent_action, action)
        self.assertEqual(player.hand_card, Card.handmaid)
        self.assertFalse(PlayerActionTools.is_blank(recent_action))
        for action in player.actions[1:]:
            self.assertTrue(PlayerActionTools.is_blank(action))
コード例 #9
0
ファイル: arena.py プロジェクト: adamschmideg/love-letter
    def compare_agents(lambda_01, lambda_02, games_to_play=51, seed=451):
        """
        Returns number of times agent created from lambda_01
        wins over agent created from lambda_02 (which plays all the other
        positions)
        """
        wins = 0
        for idx in range(games_to_play):
            game = Game.new(4, seed + idx)
            agent_one = (lambda_01)(seed + idx)
            agent_two = (lambda_02)(seed + idx)

            while game.active():
                if not game.is_current_player_playing():
                    game = game.skip_eliminated_player()
                    continue

                if game.player_turn() == 0:
                    action = agent_one.move(game)
                else:
                    action = agent_two.move(game)
                game, _ = game.move(action)

            if game.is_winner(0):
                wins = wins + 1
        return wins
コード例 #10
0
ファイル: play.py プロジェクト: adamschmideg/love-letter
def play(seed, previous_actions):
    """Play a game"""
    game = Game.new(4, seed)
    previous_actions = np.array([], dtype=np.uint8) if len(previous_actions) < 1 else \
        np.array([int(i) for i in previous_actions.split(",")], dtype=np.uint8)
    previous_actions = PlayerActionTools.from_np_many(previous_actions)[::-1]
    actions = []
    while game.active():
        if not game.is_current_player_playing():
            game = game.skip_eliminated_player()
            continue

        display(game, actions)

        try:
            if len(previous_actions) > 0:
                action = previous_actions.pop()
            else:
                print("  What card to play?")
                action = get_action()
            actions.append(action)
            game, _ = game.move(action)
        except ValueError:
            print("Invalid move - Exit with Ctrl-C")

    display(game, actions)
    print("Game Over : Player {} Wins!".format(game.winner()))
コード例 #11
0
def test_advance_roundHasEnded_startsNewRound(started_game: Game):
    game_round = started_game.current_round
    assert not game_round.ended
    force_end_round(game_round)
    new_state: loveletter.game.PlayingRound = started_game.advance()
    new_round = new_state.round
    assert new_round is not game_round
    assert started_game.current_round is new_round
    assert not new_round.started
コード例 #12
0
ファイル: test_game.py プロジェクト: user01/love-letter
 def test_new(self):
     """Getting a new game"""
     game = Game.new()
     self.assertEqual(game.draw_card(), Card.guard)
     self.assertEqual(game.round(), 0)
     self.assertEqual(game.player_turn(), 0)
     self.assertEqual(game.cards_left(), 11)
     self.assertTrue(game.active())
     self.assertFalse(game.over())
コード例 #13
0
def test_newGame_validPlayerList_works(players: List[str]):
    game = Game(players)
    assert len(game.players) == len(players)
    assert len(set(map(id, game.players))) == len(players)
    assert all(game.players[i].id == i for i in range(len(players)))
    assert not game.started
    assert game.current_round is None
    assert game.state.type == GameState.Type.INIT
    assert set(game.points).issubset(game.players)
    assert all(game.points[p] == 0 for p in game.players)
コード例 #14
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_last_player_win(self):
        """Win the game by knocking out the opposing player"""
        game = Game.new(2, 3)
        action = PlayerAction(Card.guard, 1, Card.king, 0)

        game, _ = game.move(action)

        self.assertEqual(game.round(), 0)
        self.assertEqual(game.cards_left(), 12)
        self.assertFalse(game.active())
        self.assertTrue(game.over())
        self.assertEqual(0, game.winner())
コード例 #15
0
def test_1_repeated_win():
    def round_runner(g):
        game_round = start_round_from_player_cards(
            [cards.Guard(), cards.Baron()],
            [cards.King(), cards.Princess()],
            first_player=0,
        )
        object.__setattr__(g.state, "round", game_round)  # work around frozen dataclass
        player0, player1 = game_round.players

        play_with_choices(player0, CardType.GUARD, player1, cards.Princess)
        play_random_move(player1)

        end = game_round.state
        assert end.type == RoundState.Type.ROUND_END
        assert end.winner is player0

    game = Game(["Alice", "Bob"])
    alice, bob = game.players
    game.start()
    for i in range(1, 8):
        assert game.state.round_no == i
        round_runner(game)
        game.advance()
        assert +game.points == {alice: i}

    assert game.ended
    assert game.state.winner is alice
コード例 #16
0
def find_seed(cards_str):
    """Play a game"""
    cards = set([int(s) for s in cards_str.split(',')])
    results = 0
    for idx in range(5000):
        game = Game.new(4, idx)
        # available_cards = set([player.hand_card for player in game.players()] + [game.draw_card()])
        available_cards = set([game.players()[0].hand_card] +
                              [game.draw_card()])
        if cards.issubset(available_cards):
            print("Found at {: >5}".format(idx))
            results += 1
        if results > 5:
            return
コード例 #17
0
ファイル: test_games.py プロジェクト: user01/love-letter
    def replay(seed, action_sequence=None):
        """Generate a game from a recorded set of actions"""
        action_sequence = action_sequence if action_sequence is not None else []
        action_sequence = np.array(action_sequence, dtype=np.uint8)
        action_sequence = PlayerActionTools.from_np_many(action_sequence)[::-1]
        game = Game.new(4, seed)

        while len(action_sequence) > 0:
            if not game.is_current_player_playing():
                game = game.skip_eliminated_player()
            else:
                action = action_sequence.pop()
                game = game._move(action)

        return game
コード例 #18
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_move_prince_self(self):
        """Use prince to force self discard"""
        game = Game.new(4, 2)
        action = PlayerAction(Card.prince, 0, Card.noCard, Card.noCard)
        action_other = PlayerAction(Card.handmaid, 0, Card.noCard, Card.noCard)
        game, _ = game.move(action)

        players = game.players()
        player = players[0]
        self.assertTrue(PlayerTools.is_playing(player))
        self.assertFalse(PlayerActionTools.is_blank(player.actions[0]))
        self.assertFalse(PlayerActionTools.is_blank(player.actions[1]))
        self.assertEqual(player.actions[0], action)
        self.assertEqual(player.actions[1], action_other)
        for action in player.actions[2:]:
            self.assertTrue(PlayerActionTools.is_blank(action))
コード例 #19
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_move_princess(self):
        """Commit suicide by discarding the princess"""
        game = Game.new(4, 11)
        action = PlayerAction(Card.princess, 0, Card.noCard, Card.noCard)
        game, _ = game.move(action)

        players = game.players()
        player = players[0]

        self.assertFalse(PlayerTools.is_playing(player))
        self.assertFalse(PlayerActionTools.is_blank(player.actions[0]))
        self.assertFalse(PlayerActionTools.is_blank(player.actions[1]))
        self.assertEqual(player.actions[0],
                         PlayerAction(Card.baron, 0, Card.noCard, Card.noCard))
        self.assertEqual(player.actions[1], action)

        for action in player.actions[2:]:
            self.assertTrue(PlayerActionTools.is_blank(action))
コード例 #20
0
def test_advance_roundFinished_pointsUpdateCorrectly(started_game: Game):
    game_round = started_game.current_round
    old_points = started_game.points.copy()

    autoplay_round(game_round)
    new_state = started_game.advance()
    assert not new_state.round.started
    winners = {started_game.players[p.id] for p in game_round.state.winners}
    new_points = started_game.points
    diffs = new_points - old_points
    # no negative points:
    assert not -new_points
    # at most one point per player plus the extra spy point:
    assert all(diff <= 2 for diff in diffs.values())
    # winners got at least one point each:
    assert all(diffs[p] >= 1 for p in winners)
    # at most 1 non-winner positive diff
    assert len(set(diffs.keys()) - winners) <= 1
    # at most one diff larger than 1:
    assert sum(int(diff > 1) for diff in diffs.values()) <= 1
コード例 #21
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_move_baron_failure(self):
        """Getting a baron move, with a failure"""
        game = Game.new(4, 48)
        action = PlayerAction(Card.baron, 1, Card.noCard, Card.noCard)
        game, _ = game.move(action)

        players = game.players()
        player = players[0]
        target = players[1]

        self.assertFalse(PlayerTools.is_playing(player))
        self.assertTrue(PlayerTools.is_playing(target))

        self.assertFalse(PlayerActionTools.is_blank(player.actions[0]))
        self.assertFalse(PlayerActionTools.is_blank(player.actions[1]))
        for action in player.actions[2:]:
            self.assertTrue(PlayerActionTools.is_blank(action))

        for action in target.actions:
            self.assertTrue(PlayerActionTools.is_blank(action))
コード例 #22
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_move_king(self):
        """Use king to swap hands with the target"""
        game = Game.new(4, 0)
        action = PlayerAction(Card.king, 1, Card.noCard, Card.noCard)
        game, _ = game.move(action)

        players = game.players()
        player = players[0]
        target = players[1]

        self.assertTrue(PlayerTools.is_playing(player))
        self.assertFalse(PlayerActionTools.is_blank(player.actions[0]))
        self.assertEqual(player.actions[0], action)
        self.assertEqual(player.hand_card, Card.priest)
        for action in player.actions[1:]:
            self.assertTrue(PlayerActionTools.is_blank(action))

        self.assertTrue(PlayerTools.is_playing(target))
        self.assertEqual(target.hand_card, Card.guard)
        for action in target.actions:
            self.assertTrue(PlayerActionTools.is_blank(action))
コード例 #23
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_move_prince_other(self):
        """Use prince to force another to discard"""
        game = Game.new(4, 2)
        action = PlayerAction(Card.prince, 1, Card.noCard, Card.noCard)
        action_target = PlayerAction(Card.guard, 0, Card.noCard, Card.noCard)
        game, _ = game.move(action)

        players = game.players()
        player = players[0]
        target = players[1]

        self.assertTrue(PlayerTools.is_playing(player))
        self.assertFalse(PlayerActionTools.is_blank(player.actions[0]))
        self.assertEqual(player.actions[0], action)
        for action in player.actions[1:]:
            self.assertTrue(PlayerActionTools.is_blank(action))

        self.assertTrue(PlayerTools.is_playing(target))
        self.assertFalse(PlayerActionTools.is_blank(target.actions[0]))
        self.assertEqual(target.actions[0], action_target)
        for action in target.actions[1:]:
            self.assertTrue(PlayerActionTools.is_blank(action))
コード例 #24
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_move_baron_success(self):
        """Getting a baron move, with a success"""
        game = Game.new(4, 48)
        action = PlayerAction(Card.baron, 3, Card.noCard, Card.noCard)
        game, _ = game.move(action)

        players = game.players()
        player = players[0]
        target = players[3]
        recent_action = player.actions[0]

        self.assertTrue(PlayerTools.is_playing(player))
        self.assertFalse(PlayerTools.is_playing(target))
        self.assertEqual(recent_action, action)

        self.assertFalse(PlayerActionTools.is_blank(recent_action))
        for action in player.actions[1:]:
            self.assertTrue(PlayerActionTools.is_blank(action))

        self.assertFalse(PlayerActionTools.is_blank(target.actions[0]))
        for action in target.actions[1:]:
            self.assertTrue(PlayerActionTools.is_blank(action))
コード例 #25
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_move_priest(self):
        """Getting a priest move"""
        game = Game.new(4, 5)
        action = PlayerAction(Card.priest, 1, Card.noCard, Card.noCard)
        action_expected = PlayerAction(Card.priest, 1, Card.noCard, Card.guard)
        game, _ = game.move(action)

        self.assertEqual(game.round(), 0)
        self.assertEqual(game.player_turn(), 1)
        self.assertEqual(game.cards_left(), 10)
        self.assertTrue(game.active())
        self.assertFalse(game.over())

        players = game.players()
        player = players[0]
        target = players[1]
        recent_action = player.actions[0]

        self.assertTrue(PlayerTools.is_playing(target))
        self.assertEqual(recent_action, action_expected)
        self.assertFalse(PlayerActionTools.is_blank(recent_action))
        for action in player.actions[1:]:
            self.assertTrue(PlayerActionTools.is_blank(action))
コード例 #26
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_move_guard_guess_guard(self):
        """Getting a guard move and guessing guard"""
        game = Game.new()
        action = PlayerAction(Card.guard, 1, Card.guard, 0)
        game, _ = game.move(action)

        self.assertEqual(game.round(), 0)
        self.assertEqual(game.player_turn(), 0)
        self.assertEqual(game.cards_left(), 11)
        self.assertTrue(game.active())
        self.assertFalse(game.over())

        players = game.players()
        player = players[0]
        target = players[1]
        recent_action = player.actions[0]

        self.assertTrue(PlayerTools.is_playing(player))
        self.assertEqual(player.hand_card, Card.handmaid)
        self.assertEqual(game.deck()[0], Card.guard)
        self.assertTrue(PlayerActionTools.is_blank(recent_action))
        for action in player.actions:
            self.assertTrue(PlayerActionTools.is_blank(action))
コード例 #27
0
ファイル: test_game.py プロジェクト: user01/love-letter
    def test_move_guard_failure(self):
        """Getting a guard move, with a wrong guess"""
        game = Game.new()
        action = PlayerAction(Card.guard, 1, Card.handmaid, 0)
        game, _ = game.move(action)

        self.assertEqual(game.round(), 0)
        self.assertEqual(game.player_turn(), 1)
        self.assertEqual(game.cards_left(), 10)
        self.assertTrue(game.active())
        self.assertFalse(game.over())

        players = game.players()
        player = players[0]
        target = players[1]
        recent_action = player.actions[0]

        self.assertTrue(PlayerTools.is_playing(target))
        self.assertEqual(recent_action, action)
        self.assertEqual(player.hand_card, Card.handmaid)
        self.assertFalse(PlayerActionTools.is_blank(recent_action))
        for action in player.actions[1:]:
            self.assertTrue(PlayerActionTools.is_blank(action))
コード例 #28
0
ファイル: conftest.py プロジェクト: plammens/loveletter
def started_game(new_game: Game) -> Game:
    new_game.start()
    return new_game
コード例 #29
0
ファイル: conftest.py プロジェクト: plammens/loveletter
def new_game(players) -> Game:
    return Game(players)
コード例 #30
0
ファイル: test_game.py プロジェクト: user01/love-letter
 def test_new_hand_card(self):
     """Getting a new hand card post discard"""
     self.assertEqual(Game.new_hand_card(1, [1, 2]), 2)
     self.assertEqual(Game.new_hand_card(2, [1, 2]), 1)
     self.assertEqual(Game.new_hand_card(2, [2, 2]), 2)