Exemplo n.º 1
0
    def play_hand(self, feedback_file_name, action):
        date_time = datetime.datetime.now().strftime("%m-%d-%y %H:%M:%S")
        deck = Deck()
        deck.create()
        deck.shuffle()
        hand = Hand()
        hand.get_hand(deck)
        hand.order_hand()
        hand_type = hand.hand_type()
        position = Position()
        position.current_position(self.num_players)
        position_min = position.min_open()
        r = Range(self.hand_range)
        correct_decision, hand_percent, total_cards = r.correct_decision(
            hand_type, position_min)
        min_open_hand = r.min_open_card(position_min)
        decision = Decision(action).decision()

        if self.show_feedback:
            if decision == correct_decision:
                feedback = "Correct"  # report feedback
                self.score += 1
            else:
                feedback = "Incorrect"  # report feedback
            feedback_file_name.save_hand(self.hand_num, date_time,
                                         self.hand_range, feedback, position,
                                         position_min, min_open_hand, hand,
                                         hand_type, hand_percent, decision,
                                         correct_decision, self.score)
            self.hand_num += 1
        else:
            self.hand_num += 1

        return self.hand_num
Exemplo n.º 2
0
class BlackJack21(object):
    def __init__(self, player: Player):
        _cards = [
            Ace(),
            Two(),
            Three(),
            Four(),
            Five(),
            Six(),
            Seven(),
            Eight(),
            Nine(),
            Ten(),
            K(),
            Q(),
            J(),
        ]
        self._deck = Deck(_cards)
        self._player = player
        self._tapped_cards = []
        self._score = 0

    def start(self):
        _loading()
        print('==== Embaralhando ====')
        self._deck.shuffle()
        time.sleep(1.5)
        _clear()
        print('==== Mesa pronta, podemos começar ====')
        while self._deck.has_more_cards():
            input('---- Pressione ENTER para virar uma carta jogador {} ----'.
                  format(self._player))
            tapped_card = self._deck.put_card()
            self._tapped_cards.append(tapped_card)
            print('---- Carta virada ----', tapped_card)
            print(' Calculando ...')
            self._calculate_score()
            if self._is_done():
                break
            print('=== Pontuação {} ===='.format(self._score))
        self._finish()

    def _is_done(self):
        if self._score <= 21:
            return False
        return True

    def _calculate_score(self):
        self._score = sum(
            map(lambda card: card.get_value(), self._tapped_cards))

    def _finish(self):
        _clear()
        print('==== Acabou o jogo ====')
        print('==== Calculando ====')
        _loading()
        _clear()
        print('O Resultado é: {}'.format(self._score))
Exemplo n.º 3
0
 def test_shuffle_deck(self):
     unshuffled_deck = "2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac 2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As "
     deck = Deck()
     deck.create()
     assert str(deck) == unshuffled_deck
     deck.shuffle()
     assert str(
         deck
     ) != unshuffled_deck  # There is a VERY SMALL chance the shuffled deck will still be in the same order as above after the shuffle; but I wouldn't bet on it.
     assert len(deck.cards) == 52
Exemplo n.º 4
0
    def test_desk_shuffles_cards(self, mock_shuffle):
        deck = Deck()
        cards = [
            Card(rank='7', suit='Diamonds'),
            Card(rank='3', suit='Spades')
        ]
        deck.add_cards(cards)
        deck.shuffle()

        assert mock_shuffle.called_once_with(cards)
 def test_hand_has_2_cards(self):
     from app.deck import Deck
     deck = Deck()
     deck.create()
     deck.shuffle()
     before_deal = str(deck)
     hand = Hand()
     hand.get_hand(deck)
     card1, card2 = hand.hole_cards
     assert str(card1) == before_deal[:2]
     assert str(card2) == before_deal[3:5]
     assert str(deck) == before_deal[6:]
Exemplo n.º 6
0
    def test_deck_should_be_shuffle_cards(self, random_mock):
        cards = [
            Mock(),
            Mock(),
            Mock(),
        ]
        random_mock.shuffle = MagicMock()
        deck = Deck(cards)

        deck.shuffle()

        random_mock.shuffle.assert_called_once_with(cards)
 def test_new_hand(self):
     """The two starting cards for each player consist of their pre-flop hand. Also, called the hole cards."""
     from app.deck import Deck
     deck = Deck()
     deck.create()
     deck.shuffle()
     before_deal = str(deck)
     hand = Hand()
     hand.get_hand(deck)
     assert str(
         hand
     ) == before_deal[:
                      6]  # See the test_deck module for an explanation of the number of characters.
Exemplo n.º 8
0
 def test_dealt_deck(self):
     deck = Deck()
     deck.create()
     deck.shuffle()
     assert len(deck.cards) == 52
     before_deal = str(deck)
     deck.deal_card()
     assert len(deck.cards) == 51
     deck.deal_card()
     assert len(deck.cards) == 50
     after_deal = str(deck)
     assert before_deal[
         6:] == after_deal  # The 'top' cards of the deck are being dealt out just like in live play.
Exemplo n.º 9
0
 def test_dealt_card(self):
     deck = Deck()
     deck.create()
     deck.shuffle()
     assert len(deck.cards) == 52
     before_deal = str(deck)
     top_card = deck.deal_card()
     assert len(deck.cards) == 51
     assert len(
         str(top_card)
     ) == 2  # The top card trims off the trailing whitspace (Technically, doesn't really trim. The space was added to make it easier in the str method for development and manual testing).
     assert str(
         top_card
     ) == before_deal[:
                      2]  # The first 3 characters of the random deck match the first 2 dealt for the top card + the space.
     assert before_deal[3:] == str(
         deck
     )  # The rest of the deck is still in its random shuffled order.
Exemplo n.º 10
0
 def test_shuffle_multiple_decks(self):
     unshuffled_deck = "2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac 2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As "
     deck1 = Deck()
     deck1.create()
     deck2 = Deck()
     deck2.create()
     assert str(deck1) == str(
         deck2
     ) == unshuffled_deck  # Same string results before the shuffle.
     assert deck1 != deck2  # Still different in memory because they were created as objects.
     deck1.shuffle()
     deck2.shuffle()
     assert str(deck1) != str(deck2) != unshuffled_deck
     assert len(str(deck1)) == len(str(deck2)) == len(
         unshuffled_deck
     ) == 156  # The character length of each deck is 156 because there are 52 cards with a length of 2 + a space that separates them.
     assert len(deck1.cards) == len(deck2.cards) == 52
     assert str(deck1.cards) != str(
         deck2.cards
     )  # Both decks always have 52 cards, but they are in a random order after the shuffle.
Exemplo n.º 11
0
class Game:
    round_counter = 0

    def __init__(self, num_decks):
        self.deck = Deck()

        std_deck = list(self.deck.cards)
        for i in range(1, num_decks):
            self.deck.cards += std_deck

        self.player = Player()
        self.dealer = Player()

    def round(self):
        self.round_counter += 1
        if self.round_counter > 1:
            input("Press Enter to start next round...")
        print("Round {} started".format(self.round_counter))

        if not self.deck.get_cards():
            self.deck = Deck()

        self.deck.shuffle()

        self.player.hit(self.deck.deal())
        self.dealer.hit(self.deck.deal())
        self.print_state()

        while self.player.playing:
            if self.player.calc_hand() > 21:
                print("You have too much :(")
                self.player.playing = False
                break
            if self.player.calc_hand() == 21:
                print("You have 21!")
                self.player.playing = False
                break

            choice = input("Want to [hit] or [stop]? ")
            while choice not in {"hit", "stop"}:
                choice = input("Wrong command. Want to [hit] or [stop]? ")
            if choice == "hit":
                self.player.hit(self.deck.deal())
            if choice == "stop":
                self.player.playing = False
            self.print_state()

        if not self.player.calc_hand() > 21:
            while self.dealer.calc_hand() < 17:
                self.dealer.hit(self.deck.deal())
                self.print_state()
            self.dealer.playing = False

        winner = self.get_winner()
        if winner == self.player:
            self.player.wins += 1
            print("Player won!")
        elif winner == self.dealer:
            self.dealer.wins += 1
            print("Dealer won")
        else:
            self.player.wins += 1
            self.dealer.wins += 1
            print("Push")

        print("Current win rate is: {:.1%}\n".format(self.player.wins /
                                                     self.round_counter))

        self.reset()

    def reset(self):
        self.player.playing = True
        self.dealer.playing = True
        self.player.reset_hand()
        self.dealer.reset_hand()

    def print_state(self):
        print("Player's hand is:")
        self.player.print_hand()

        print("Dealer's hand is:")
        self.dealer.print_hand()

        print("Actual score is: {}:{}\n".format(self.player.calc_hand(),
                                                self.dealer.calc_hand()))

    def get_winner(self):
        if (self.player.calc_hand() > self.dealer.calc_hand() or self.dealer.calc_hand() > 21)\
                and not self.player.calc_hand() > 21:
            return self.player
        elif self.player.calc_hand() < self.dealer.calc_hand(
        ) or self.player.calc_hand() > 21:
            return self.dealer
        else:
            return None
    def play_hand(self, feedback_file_name):
        date_time = datetime.datetime.now().strftime("%m-%d-%y %H:%M:%S")
        print("Hand number: " + str(self.hand_num))

        deck = Deck()
        deck.create()
        deck.shuffle()

        hand = Hand()
        hand.get_hand(deck)
        print(hand)

        hand.order_hand()
        hand_type = hand.hand_type()

        position = Position()
        position.current_position(self.num_players)
        print(position)

        position_min = position.min_open()

        r = Range(self.hand_range)
        correct_decision, hand_percent, total_cards = r.correct_decision(
            hand_type, position_min)
        # Leaving the following several print statements for reference in case someone else isn't that familiar with hand range calculations.
        # print(correct_decision)
        # print(hand_percent)
        # print(total_cards)  # To confirm the hand percentage is correct: total_cards / 1326 = hand_percent

        min_open_hand = r.min_open_card(position_min)
        # print(min_open_hand)

        action = int(input("What is your decision? (4=Open, 6=Fold): ")
                     )  # For faster keyboard input
        decision = Decision(action).decision()

        if decision != "stop":
            if self.show_feedback:
                if decision == correct_decision:
                    # screen feedback
                    print(
                        "Good job! You should", correct_decision,
                        "because you want to play the top {0:.2f}".format(
                            position_min * 100) +
                        "% of your range; which ends at " +
                        str(min_open_hand) + ".\n" + str(hand) +
                        "is in the top {0:.2f}".format(hand_percent * 100) +
                        "% of starting hands for the " + self.hand_range +
                        " range.")
                    feedback = "Correct"  # report feedback
                    self.score += 1
                else:
                    print(
                        "Sorry, you should", correct_decision,
                        "because you want to play the top {0:.2f}".format(
                            position_min * 100) +
                        "% of your range; which ends at " +
                        str(min_open_hand) + ".\n" + str(hand) +
                        "is in the top {0:.2f}".format(hand_percent * 100) +
                        "% of starting hands for the " + self.hand_range +
                        " range.")
                    feedback = "Incorrect"  # report feedback
                feedback_file_name.save_hand(self.hand_num, date_time,
                                             self.hand_range, feedback,
                                             position, position_min,
                                             min_open_hand, hand, hand_type,
                                             hand_percent, decision,
                                             correct_decision, self.score)
                self.hand_num += 1
                print("Score: " + str(self.score) + "\n")
            else:
                self.hand_num += 1
                print()
        else:
            print("Thanks for playing.")

        return action
Exemplo n.º 13
0
 def test_out_of_cards(self):
     """For this game we are only concerned about the first two cards. However, if this was expanded to post flop the game flow could be like this.
     px = player number, cx = card number, xb = street burn card, fx = flop card, t = turn, r = river, ccx = count remaining cards."""
     deck = Deck()
     deck.create()
     deck.shuffle()
     assert len(deck.cards) == 52
     before_deal = str(deck)
     p1c1 = deck.deal_card()
     p1c2 = deck.deal_card()
     p2c1 = deck.deal_card()
     p2c2 = deck.deal_card()
     p3c1 = deck.deal_card()
     p3c2 = deck.deal_card()
     p4c1 = deck.deal_card()
     p4c2 = deck.deal_card()
     p5c1 = deck.deal_card()
     p5c2 = deck.deal_card()
     p6c1 = deck.deal_card()
     p6c2 = deck.deal_card()
     p7c1 = deck.deal_card()
     p7c2 = deck.deal_card()
     p8c1 = deck.deal_card()
     p8c2 = deck.deal_card()
     p9c1 = deck.deal_card()
     p9c2 = deck.deal_card()
     p10c1 = deck.deal_card()
     p10c2 = deck.deal_card(
     )  # At a full table (10 players) this would complete the preflop deal.
     assert len(
         deck.cards
     ) == 32  # 32 cards are left; which is more than enough for the community cards.
     assert p1c1 != p1c2 != p2c1 != p2c2 != p3c1 != p3c2 != p4c1 != p4c2 != p5c1 != p5c2 != p6c1 != p6c2 != p7c1 != p7c2 != p8c1 != p8c2 != p9c1 != p9c2 != p10c1 != p10c2  # All the cards are different.
     assert before_deal[60:] == str(deck)
     bf = deck.deal_card(
     )  # Burning cards is done in live play to help prevent cheating and isn't really necessary online. Regardless, we still have enough cards either way.
     f1 = deck.deal_card()
     f2 = deck.deal_card()
     f3 = deck.deal_card()
     bt = deck.deal_card()
     t = deck.deal_card()
     br = deck.deal_card()
     r = deck.deal_card()
     assert len(
         deck.cards
     ) == 24  # 24 cards are left; which sometimes you'll see the dealer count out to confirm all the cards are there.
     assert bf != f1 != f2 != f3 != bt != t != br != r
     assert before_deal[84:] == str(deck)
     cc1 = deck.deal_card()
     cc2 = deck.deal_card()
     cc3 = deck.deal_card()
     cc4 = deck.deal_card()
     cc5 = deck.deal_card()
     cc6 = deck.deal_card()
     cc7 = deck.deal_card()
     cc8 = deck.deal_card()
     cc9 = deck.deal_card()
     cc10 = deck.deal_card()
     cc11 = deck.deal_card()
     cc12 = deck.deal_card()
     cc13 = deck.deal_card()
     cc14 = deck.deal_card()
     cc15 = deck.deal_card()
     cc16 = deck.deal_card()
     cc17 = deck.deal_card()
     cc18 = deck.deal_card()
     cc19 = deck.deal_card()
     cc20 = deck.deal_card()
     cc21 = deck.deal_card()
     cc22 = deck.deal_card()
     cc23 = deck.deal_card()
     cc24 = deck.deal_card()
     assert len(deck.cards) == 0
     assert cc1 != cc2 != cc3 != cc4 != cc5 != cc6 != cc7 != cc8 != cc9 != cc10 != cc11 != cc12 != cc13 != cc14 != cc15 != cc16 != cc17 != cc18 != cc19 != cc20 != cc21 != cc22 != cc23 != cc24  # All different.
     assert str(
         deck
     ) == "Sorry, no cards in deck. Please create a new deck; and then, shuffle up and deal."
     cc25 = deck.deal_card()  # This card doesn't exist.
     assert str(cc25) == "Sorry, unable to continue dealing because we are out of cards.\n" \
                         "This is somewhat odd because community card games (like No Limit Texas Hold'em) came about because many players don't like to fold.\n" \
                         "As a result, the community cards (the board consisting of the flop, turn, and river) should prevent this.\n" \
                         "Regardless, please create a new deck; and then, shuffle up and deal."
Exemplo n.º 14
0
 def test_no_deck_created(self):
     deck = Deck()
     deck.shuffle()
     assert str(
         deck
     ) == "Sorry, no cards in deck. Please create a new deck; and then, shuffle up and deal."