Beispiel #1
0
def test_showdown_no_show():
    test_players = [
        PlayerInHand(session_id="ls", bet=0, eligibility=None, has_option=False),
        # Want this player to win first
        PlayerInHand(session_id="w", bet=0, eligibility=20, has_option=False),
        PlayerInHand(session_id="lb", bet=0, eligibility=None, has_option=False),
    ]
    finished_game = Game(
        players=test_players,
        stage=Stage.RIVER,
        pot=max(tp.eligibility or 0 for tp in test_players),
        #     ls     w      wb     lb     community
        deck=("2H3D" "AHAS" "ADAC" "XDXS" "3C9S5DJSQC"),
    )
    room = MockRoom()
    room.players = {
        "ls": Player(balance=7, name="loser", pending_balance=0),
        "w": Player(balance=0, name="winner", pending_balance=0),
        "lb": Player(balance=12, name="alsoloser", pending_balance=0),
    }

    finished_game.pay_winners(room)
    assert room.players["ls"].balance == 7
    assert room.players["w"].balance == 20
    assert room.players["lb"].balance == 12
    assert finished_game.pot == 0
    assert set(room.log[0].players.keys()) == set(("w",))
    # Should not have shown down
    assert room.log[0].players["w"].hand is None
    def test_deals_each_player_3_flop_1_turn_1_river_cards(self):
        mock_player1 = MagicMock()
        mock_player1.wants_to_fold.return_value = False
        mock_player2 = MagicMock()
        mock_player2.wants_to_fold.return_value = False
        players = [mock_player1, mock_player2]

        mock_deck = MagicMock()
        mock_deck.remove_cards.side_effect = [
            self.first_two_cards, self.next_two_cards, self.flop_cards,
            self.turn_card, self.river_card
        ]

        game = Game(deck=mock_deck, players=players)
        game.play()

        mock_deck.remove_cards.assert_has_calls([call(3), call(1), call(1)])

        calls = [
            call(self.flop_cards),
            call(self.turn_card),
            call(self.river_card)
        ]

        for player in players:
            player.add_cards.assert_has_calls(calls)
Beispiel #3
0
def test_sidepot_1():
    test_players = [
        PlayerInHand(session_id="ls", bet=0, eligibility=None, has_option=False),
        # Want w and wb to split the pot
        PlayerInHand(session_id="w", bet=0, eligibility=10, has_option=False),
        PlayerInHand(session_id="wb", bet=0, eligibility=20, has_option=False),
        # This player should unevenly lose their chips
        PlayerInHand(session_id="lb", bet=0, eligibility=20, has_option=False),
    ]
    finished_game = Game(
        players=test_players,
        stage=Stage.RIVER,
        pot=max(tp.eligibility or 0 for tp in test_players),
        #     ls     w      wb     lb     community
        deck=("2H3D" "AHAS" "ADAC" "XDXS" "3C9S5DJSQC"),
    )
    room = MockRoom()
    room.players = {
        "ls": Player(balance=7, name="loser", pending_balance=0),
        "w": Player(balance=0, name="winner", pending_balance=0),
        "lb": Player(balance=12, name="alsoloser", pending_balance=0),
        "wb": Player(balance=10, name="bigwinner", pending_balance=0),
    }

    finished_game.pay_winners(room)
    assert room.players["ls"].balance == 7
    assert room.players["w"].balance == 5
    assert room.players["wb"].balance == 25
    assert room.players["lb"].balance == 12
    assert finished_game.pot == 0
Beispiel #4
0
def test_sidepot_random(monkeypatch):
    monkeypatch.setattr(game, "random", Random(0))

    test_players = [
        PlayerInHand(session_id="ls", bet=0, eligibility=3, has_option=False),
        # Want this player to win first
        PlayerInHand(session_id="w", bet=0, eligibility=5, has_option=False),
        # But then these players split because hilarious raisins
        PlayerInHand(session_id="wb", bet=0, eligibility=8, has_option=False),
        PlayerInHand(session_id="lb", bet=0, eligibility=8, has_option=False),
    ]
    finished_game = Game(
        players=test_players,
        stage=Stage.RIVER,
        pot=max(tp.eligibility for tp in test_players),
        deck=_make_deck(len(test_players)),
    )
    room = MockRoom()
    room.players = {
        "ls": Player(balance=0, name="loser", pending_balance=0),
        "w": Player(balance=0, name="winner", pending_balance=0),
        "lb": Player(balance=12, name="alsoloser", pending_balance=0),
        "wb": Player(balance=10, name="bigwinner", pending_balance=0),
    }

    finished_game.pay_winners(room)
    assert room.players["w"].balance == 5
    # Should split between wb and lb
    assert room.players["wb"].balance == 11
    assert room.players["lb"].balance == 13
    # Should leave 1 chip in the pot for the next round
    assert finished_game.pot == 1
    assert set(room.log[0].players.keys()) == set(("w", "lb", "wb"))
Beispiel #5
0
def test_normal_pot(monkeypatch):
    monkeypatch.setattr(game, "random", Random(0))

    test_players = [
        PlayerInHand(session_id="ls", bet=0, eligibility=5, has_option=False),
        PlayerInHand(session_id="w", bet=0, eligibility=5, has_option=False),
        PlayerInHand(session_id="lb", bet=0, eligibility=5, has_option=False),
    ]
    finished_game = Game(
        players=test_players,
        stage=Stage.RIVER,
        pot=max(tp.eligibility for tp in test_players),
        deck=_make_deck(len(test_players)),
    )
    room = MockRoom()
    room.players = {
        "ls": Player(balance=10, name="loser", pending_balance=0),
        "w": Player(balance=20, name="winner", pending_balance=0),
        "lb": Player(balance=40, name="alsoloser", pending_balance=0),
    }

    finished_game.pay_winners(room)
    assert room.players["ls"].balance == 10
    assert room.players["w"].balance == 25
    assert room.players["lb"].balance == 40
    def test_game_play_shuffles_deck(self):
        mock_deck = MagicMock()
        players = [MagicMock(), MagicMock()]

        game = Game(deck=mock_deck, players=players)

        game.play()
        mock_deck.shuffle.assert_called_once()
Beispiel #7
0
def test_deal_hole():
    n_players = 6
    game = Game(n_players)
    game.deal_hole()
    player_n_cards = np.array([len(player.hand) for player in game.players])
    assert all(player_n_cards == 2), \
        'Not all players have two cards after dealing hole cards'
    assert len(game.deck) + sum(player_n_cards) == 52, \
        'Some cards have gone missing after dealing hole'
Beispiel #8
0
def test_prepare_deck():
    n_players = 5
    game = Game(n_players)
    assert len(game.deck) == 52, 'Too many cards to start'

    ex_cards = [[1, 9], [3, 4], [2, 2]]
    game.prepare_deck(excluded_cards=ex_cards)
    assert len(game.deck) == (52 - len(ex_cards)), \
        'Card exclusion when preparing deck not working'
    def test_removes_player_if_not_willing_to_bet(self):
        deck = MagicMock()
        player1 = MagicMock()
        player2 = MagicMock()

        player1.wants_to_fold.return_value = True
        player2.wants_to_fold.return_value = False
        players = [player1, player2]

        game = Game(deck=deck, players=players)
        game.play()

        self.assertEqual(game.players, [player2])
Beispiel #10
0
def test_determine_winner_3():
    """
    Winner has a full house, but make sure that it uses the highest value 
    full house
    """
    game = Game(n_players=2)

    # Full house with a pair of 2s
    player_1_cards = [
        dict(suit=1, value=8, name='dummy_name'),
        dict(suit=2, value=8, name='dummy_name_2'),
        dict(suit=3, value=8, name='dummy_name_3'),
        dict(suit=2, value=4, name='dummy_name_4'),
        dict(suit=3, value=4, name='dummy_name_5'),
        dict(suit=3, value=2, name='dummy_name_6'),
        dict(suit=0, value=2, name='dummy_name_7')
    ]
    for card in player_1_cards:
        game.players[0].hand = \
            game.players[0].hand.append(card, ignore_index=True)
    game.players[0].hand.reset_index(drop=True, inplace=True)

    # Two pairs
    player_2_cards = [
        dict(suit=1, value=8, name='dummy_name'),
        dict(suit=2, value=9, name='dummy_name_2'),
        dict(suit=3, value=8, name='dummy_name_3'),
        dict(suit=2, value=4, name='dummy_name_4'),
        dict(suit=1, value=4, name='dummy_name_5'),
        dict(suit=2, value=2, name='dummy_name_6'),
        dict(suit=0, value=2, name='dummy_name_7')
    ]
    for card in player_2_cards:
        game.players[1].hand = \
            game.players[1].hand.append(card, ignore_index=True)
    game.players[1].hand.reset_index(drop=True, inplace=True)

    for player in game.players:
        player.determine_hand()
    assert game.players[0].hand_score.loc['Full house', 'high_card'] == 8.04
    assert \
        sorted(game.players[0].hand_score.loc['Full house', 'required_cards']) == \
        sorted([[1, 8], [2, 8], [3, 8], [2, 4], [3, 4]])

    print(game.players[0].hand_score)
    winners = game.determine_winner()
    assert game.players[0] in winners, 'Winner not in winners list'
    assert game.players[1] not in winners, 'Loser in winners list'
Beispiel #11
0
def test_init():
    n_players = 5
    game = Game(n_players)
    assert len(game.players) == n_players, 'Wrong number of players assigned'

    dealership = [player.is_dealer for player in game.players]
    assert sum(dealership) == 1, 'Should only be one dealer'
Beispiel #12
0
    def test_stores_deck_and_players(self):
        deck = MagicMock()
        players = [MagicMock(), MagicMock()]

        game = Game(deck=deck, players=players)

        self.assertEqual(game.deck, deck)

        self.assertEqual(game.players, players)
Beispiel #13
0
def test_simulate():
    game = Game(n_players=2)
    player_1_cards = [[1, 8], [2, 8]]
    for card in player_1_cards:
        game.deal_card(recipient=game.user, card=card)
    game.simulate()
    assert game.user.hand_score.loc['Pair', 'probability_of_occurring'] == 1
Beispiel #14
0
def test_determine_winner_1():
    game = Game(n_players=2)

    # Give player 1 two pairs of 8s and 4s, and another pair of 2s
    player_1_cards = [
        dict(suit=1, value=8, name='dummy_name'),
        dict(suit=2, value=8, name='dummy_name_2'),
        dict(suit=1, value=4, name='dummy_name_3'),
        dict(suit=2, value=4, name='dummy_name_4'),
        dict(suit=3, value=2, name='dummy_name_5'),
        dict(suit=3, value=2, name='dummy_name_6'),
        dict(suit=4, value=9, name='dummy_name_7')
    ]
    for card in player_1_cards:
        game.players[0].hand = \
            game.players[0].hand.append(card, ignore_index=True)
    game.players[0].hand.reset_index(drop=True, inplace=True)

    # Give player 2 two pairs of 8s and 3s, and another pair of 2s
    player_2_cards = [
        dict(suit=1, value=8, name='dummy_name'),
        dict(suit=2, value=8, name='dummy_name_2'),
        dict(suit=1, value=3, name='dummy_name_3'),
        dict(suit=2, value=3, name='dummy_name_4'),
        dict(suit=3, value=2, name='dummy_name_5'),
        dict(suit=3, value=2, name='dummy_name_6'),
        dict(suit=4, value=9, name='dummy_name_7')
    ]
    for card in player_2_cards:
        game.players[1].hand = \
            game.players[1].hand.append(card, ignore_index=True)
    game.players[1].hand.reset_index(drop=True, inplace=True)

    for player in game.players:
        player.determine_hand()
    print(game.players[0].hand_score)
    winners = game.determine_winner()
    assert game.players[0] in winners, 'Winner not in winners list'
    assert game.players[1] not in winners, 'Loser in winners list'
Beispiel #15
0
    def test_deals_two_initial_cards_to_each_player(self):

        mock_deck = MagicMock()
        mock_deck.remove_cards.side_effect = [
            self.first_two_cards, self.next_two_cards,
            MagicMock(),
            MagicMock(),
            MagicMock()
        ]

        mock_player1 = MagicMock()
        mock_player2 = MagicMock()
        mock_players = [mock_player1, mock_player2]

        game = Game(deck=mock_deck, players=mock_players)

        game.play()
        mock_deck.remove_cards.assert_has_calls([
            call(2),
            call(2)  #since each player receives 2 cards
        ])

        mock_player1.add_cards.assert_has_calls([call(self.first_two_cards)])
        mock_player2.add_cards.assert_has_calls([call(self.next_two_cards)])
Beispiel #16
0
def index():
    form = HoleForm()

    if request.method == 'POST':
        app.config['game'] = Game(n_players=form.n_players.data,
                                  simulation_iterations=50,
                                  parallelise=True)
        card_1 = [int(form.card_1_suit.data), int(form.card_1_values.data)]
        card_2 = [int(form.card_2_suit.data), int(form.card_2_values.data)]
        users_cards = [card_1, card_2]
        for card in users_cards:
            app.config['game'].deal_card(recipient=app.config['game'].user,
                                         card=card)
        app.config['game'].simulate()
        return redirect('hole')

    return render_template('index.html', form=form)
Beispiel #17
0
def test_deal_card():
    n_players = 6
    game = Game(n_players)
    game.deal_hole()
    deck_size = len(game.deck)
    community_card_size = len(game.community_cards)

    game.deal_card()
    new_deck_size = len(game.deck)
    new_community_card_size = len(game.community_cards)

    deck_difference = new_deck_size - deck_size
    community_difference = new_community_card_size - community_card_size
    assert community_difference == -deck_difference, \
        'Cards have gone missing on dealing to community'

    game.deal_card(game.players[0])
    assert len(game.players[0].hole) == 3, \
        'Player has not received dealt card'
Beispiel #18
0
def test_app_game():

    app.config['game'] = Game(n_players=4,
                              simulation_iterations=5,
                              parallelise=False)

    users_cards = [[0, 6], [1, 6]]
    for card in users_cards:
        app.config['game'].deal_card(recipient=app.config['game'].user,
                                     card=card)
    app.config['game'].simulate()

    flop_cards = [[1, 11], [0, 4], [2, 5]]
    app.config['game'].deal_community(cards=flop_cards)
    app.config['game'].simulate()

    turn_card = [[2, 6]]
    app.config['game'].deal_community(cards=turn_card)
    app.config['game'].simulate()

    river_card = [[3, 9]]
    app.config['game'].deal_community(cards=river_card)
    app.config['game'].simulate()
Beispiel #19
0
def test_determine_winner_2():
    """
    Same hand, but one has a better pair in reserve that can't be used due
    to not enough cards left in 5-card hand, so high card wins
    """
    game = Game(n_players=2)

    player_1_cards = [[1, 8], [2, 8], [1, 4], [2, 4], [3, 2], [2, 2], [0, 10]]
    for card in player_1_cards:
        game.deal_card(recipient=game.players[0], card=card)

    # Give player 2 two pairs of 8s and 3s, and another pair of 2s
    player_2_cards = [[0, 8], [3, 8], [0, 4], [3, 4], [1, 3], [2, 3], [0, 9]]
    for card in player_2_cards:
        game.deal_card(recipient=game.players[1], card=card)

    for player in game.players:
        player.determine_hand()

    winners = game.determine_winner()
    assert game.players[0] in winners, 'Winner not in winners list'
    assert game.players[1] not in winners, 'Loser in winners list'
Beispiel #20
0
from poker.player import Player

deck = Deck()
cards = Card.create_standard_52_cards()
deck.add_cards(cards)

hand1 = Hand()
hand2 = Hand()
hand3 = Hand()

player1 = Player(name="Leo", hand=hand1)
player2 = Player(name="Rodrigo", hand=hand2)
player3 = Player(name="Diego", hand=hand3)
players = [player1, player2, player3]

game = Game(deck=deck, players=players)
game.play()

for player in players:
    index, hand_name, hand_cards = player.best_hand()
    hand_cards_strings = [str(card) for card in hand_cards]
    hand_cards_string = " and ".join(hand_cards_strings)
    print(
        f"{player.name} has a {hand_name} with the following hand: {hand_cards_string}."
    )

winners_list_name = [max(players).name]
copy = players[:]
copy.remove(max(players))
for player in copy:
    if player == max(players):
Beispiel #21
0
    def play(self):
        while self.prepared():
            Game(self.game_id, self.table).play()

        print('Game over')
Beispiel #22
0
async def on_message(message):
    guild = message.guild
    channel = message.channel
    send = channel.send  # this is a function
    author = message.author
    msg = message.content

    # clear empty games
    global games
    games = [game for game in games if game.active]

    # don't respond to self
    if author == client.user or not is_command(msg):
        return

    print(
        f"Received command attempt \"{msg}\" from {author} in {channel} in {guild}"
    )

    parts = extract_parts(msg)
    cmd = parts[0]
    args = parts[1:]

    if cmd in ["hello", "hi", "hey"]:
        await send(f"Hello, {author.mention}! :smile:")

    elif cmd in ["where", "whereami"]:
        await send(
            f"We are in the server **{guild.name}** in the channel {channel.mention}! :smile:"
        )

    elif cmd in ["die", "dice"]:
        await send(f"Rolled a {random.choice(range(1, 6))}.")

    elif cmd in ["coin", "coinflip"]:
        await send(
            f"Flipped {'Heads' if (random.random() > 0.5) else 'Tails'}.")

    # TODO: disallow people already in games
    elif cmd in ["game", "startgame", "start"]:
        pre_message = f"{author.mention} is starting a poker game! React to this message to join! "
        game_message = await send(pre_message +
                                  f"{JOIN_TIMEOUT} seconds left!")
        await game_message.add_reaction("✅")

        await sleep(JOIN_TIMEOUT / 4)

        for i in range(3, 0, -1):
            await game_message.edit(content=pre_message +
                                    f"{i / 4 * JOIN_TIMEOUT} seconds left!")
            await sleep(JOIN_TIMEOUT / 4)

        reactors = [author]
        cache_msg = discord.utils.get(client.cached_messages,
                                      id=game_message.id)

        for reaction in cache_msg.reactions:
            async for user in reaction.users():
                if user.id not in [r.id
                                   for r in reactors] and user != client.user:
                    reactors.append(user)
                if len(reactors) == MAX_PLAYERS:
                    break
            else:
                continue
            break

        if len(reactors) < 2:
            await game_message.edit(
                content=
                f"Not enough players reacted; the game is cancelled. :slight_frown:"
            )
            await game_message.clear_reactions()
            return

        await game_message.edit(
            content=f"{author.mention} has started a poker game! "
            f"Players: {english_list(reactors, lambda r: r.mention)}")
        await game_message.clear_reactions()

        game = Game(reactors, client)
        games.append(game)
        await game.deal_to_all()
        # await game.send_embed()
        await game.round()

    elif cmd in ["game?"]:
        game = discord.utils.find(lambda g: author in g.players, games)

        if game:
            players_but = [p for p in game.players if p != author]
            await send(
                f"You are in a game with {english_list(players_but, lambda p: p.mention)}."
            )
        else:
            await send("You are not currrently in a game.")