Exemple #1
0
class DeckTests(unittest.TestCase):
    def setUp(self):
        self.deck = Deck()

    def test_init(self):
        self.assertTrue(isinstance(self.deck.cards, list))
        self.assertEqual(len(self.deck.cards), 52)

    def test_repr(self):
        self.assertEqual(repr(self.deck), 'Deck of 52 cards')

    def test_count(self):
        self.assertEqual(self.deck.count(), 52)
        self.deck.cards.pop()
        self.assertEqual(self.deck.count(), 51)

    def test_deal_sufficient_cards(self):
        cards = self.deck._deal(10)
        self.assertEqual(len(cards), 10)
        self.assertEqual(self.deck.count(), 42)

    def test_deal_insufficient_cards(self):
        cards = self.deck._deal(100)
        self.assertEqual(len(cards), 52)
        self.assertEqual(self.deck.count(), 0)

    def test_deal_no_cards(self):
        self.deck._deal(self.deck.count())
        with self.assertRaises(ValueError):
            self.deck._deal(1)

    def test_deal_card(self):
        card = self.deck.cards[-1]
        dealt_card = self.deck.deal_card()
        self.assertEqual(card, dealt_card)
        self.assertEqual(self.deck.count(), 51)

    def test_deal_hand(self):
        cards = self.deck.deal_hand(20)
        self.assertEqual(len(cards), 20)
        self.assertEqual(self.deck.count(), 32)

    def test_shuffle_full_deck(self):
        cards = self.deck.cards[:]
        self.deck.shuffle()
        self.assertNotEqual(cards, self.deck.cards)
        self.assertEqual(self.deck.count(), 52)

    def test_shuffle_not_full_deck(self):
        self.deck.deal(1)
        with self.assertRaises(ValueError):
            self.deck.shuffle()
Exemple #2
0
class Env:
    def __init__(self, conf):
        self.players = conf['players']
        self.players.append("local")
        self.floor = conf['floor']
        self.nb_card = conf['nb_card']
        self.nb_round = conf['nb_round']

        random.shuffle(self.players)

    def reset(self):
        self.board = Board(self.floor)
        self.deck = Deck()
        self.deck.deal(len(self.players), self.nb_card)
Exemple #3
0
class Blackjack(object):
    def __init__(self):
        self._deck = Deck()
        self._deck.shuffle()

        # Pass the player and dealer two cards each
        self._player = Player([self._deck.deal(), self._deck.deal()])
        self._dealer = Dealer([self._deck.deal(), self._deck.deal()])

    def play(self):
        print("Player:\n", self._player)
        print("Dealer:\n", self._dealer)

        # Player hits until user says NO
        while True:
            choice = input("Do you want a hit? [y/n]: ")
            if choice in ("Y", "y"):
                self._player.hit(self._deck.deal())
                points = self._player.getPoints()
                print("Player:\n", self._player)
                if points >= 21:
                    break
            else:
                break
        playerPoints = self._player.getPoints()
        if playerPoints > 21:
            print("You bust and lose")
        else:
            # Dealer's turn to hit
            self._dealer.hit(self._deck)
            print("Dealer:\n", self._dealer)
            dealerPoints = self._dealer.getPoints()

            # Determine the outcome
            if dealerPoints > 21:
                print(" Dealer busts and you win")
            elif dealerPoints > playerPoints:
                print("Dealer wins")
            elif dealerPoints < playerPoints and playerPoints <= 21:
                print("You win")
            elif dealerPoints == playerPoints:
                if self._player.hasBlackjack() and \
                        not self._dealer.hasBlackjack():
                    print("You win")
                elif not self._player.hasBlackjack() and \
                        self._dealer.hasBlackjack():
                    print("Dealer wins")
                else:
                    print("There is a tie")
Exemple #4
0
    def play(self):
        poker_players = []

        num_players = input("How many players? ")
        for i in range(int(num_players)):
            player_name = input("Name of poker player {}? ".format(i + 1))
            poker_player = PokerPlayer(player_name)
            poker_players.append(poker_player)

        print("Dealing cards")
        deck = Deck()
        deck.shuffle()
        for i in range(7):
            for poker_player in poker_players:
                poker_player.add_card(deck.deal())
                print(poker_player)

            if (i < 6):
                dealmore = input("Deal more card(y or n)? ")
                if (dealmore.lower() == 'n'):
                    return

        for poker_player in poker_players:
            poker_player.review_all_fiver_hands()
            poker_score = poker_player.get_top_poker_score()
            print(poker_player.name.center(30, '-'))
            print(poker_score)
Exemple #5
0
    def __init__(self, players, verbose=False):
        """
        players is a list of four players
        """
        self.verbose = verbose
        if len(players) != 4:
            raise ValueError('There must be four players.')
        self.players = players

        # Invariant: the union of these lists makes up exactly one deck of cards
        deck = Deck()
        self._player_hands = tuple(deck.deal())
        self._cards_taken = ([], [], [], [])
Exemple #6
0
    def __init__(self, players, verbose=False):
        """
        players is a list of four players
        """
        self.verbose = verbose
        if len(players) != 4:
            raise ValueError('There must be four players.')
        self.players = players

        # Invariant: the union of these lists makes up exactly one deck of cards
        deck = Deck()
        self._player_hands = tuple(deck.deal())
        self._cards_taken = ([], [], [], [])
Exemple #7
0
class CardDemo(Frame):
    def __init__(self):
        """Sets up the window and widgets."""
        Frame.__init__(self)
        self.master.title("Card Demo")
        self.grid()
        self._deck = Deck()
        self._backImage = PhotoImage(file=Card.BACK_NAME)
        self._cardImage = None
        self._imageLabel = Label(self, image=self._backImage)
        self._imageLabel.grid(row=0, column=0, rowspan=3)
        self._textLabel = Label(self, text="")
        self._textLabel.grid(row=3, column=0)

        # DealButton
        self._dealButton = Button(self, text="Deal", command=self._deal)
        self._dealButton.grid(row=0, column=1)
        # ShuffleButton
        self._shuffleButton = Button(self,
                                     text="Shuffle",
                                     command=self._shuffle)
        self._shuffleButton.grid(row=1, column=1)
        # newButton
        self._newButton = Button(self, text="New Deck", command=self._new)
        self._newButton.grid(row=2, column=1)

    def _deal(self):
        """If the deck is not empty, deals and display the
        next card.  Otherwise, returns the program to its
        initial state."""
        card = self._deck.deal()
        if card != None:
            self._cardImage = PhotoImage(file=card.fileName)
            self._imageLabel["image"] = self._cardImage
            self._textLabel["text"] = str(card)
        else:
            self._new()

    def _shuffle(self):
        self._deck.shuffle()

    def _new(self):
        """Returns the program to its initial state."""
        self._deck = Deck()
        self._cardImage = None
        self._imageLabel["image"] = self._backImage
        self._textLabel["text"] = ""
Exemple #8
0
    def reset(self):
        self.trick_nr = 0

        self.current_player_idx = 0

        self.trick = []
        self.trick_cards = []
        for _ in range(13):
            self.trick_cards.append([None, None, None, None])

        self.player_scores = [0, 0, 0, 0]
        self.player_action_pos = [[0] * 13, [0] * 13, [0] * 13, [0] * 13]

        self.expose_info = [1, 1, 1, 1]
        self.take_pig_card = False
        self.is_heart_broken = False
        self.is_shootmoon = False

        for i in range(4):
            self.players[i].set_position(i)
            self.players[i].reset()

        deck = Deck()

        self._player_hands = list(deck.deal())
        self._cards_taken = ([], [], [], [])
        self._b_cards_taken = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],
                               [0, 0, 0, 0]]
        self._temp_score = [0, 0, 0, 0]

        self.lacking_cards = []
        for _ in range(4):
            self.lacking_cards.append({
                Suit.spades: False,
                Suit.hearts: False,
                Suit.diamonds: False,
                Suit.clubs: False
            })
Exemple #9
0
class DeckTestCase(unittest.TestCase):
    def setUp(self):
        self.full_deck = Deck()
        self.empty_deck = Deck()

        while len(self.empty_deck.get_cards()) > 0:
            self.empty_deck.remove_random_card()

    @staticmethod
    def generate_full_deck():
        cards = []
        for val in range(2, 15):
            for suit in ["Hearts", "Diamonds", "Spades", "Clubs"]:
                cards.append((val, suit))

        return cards

    @staticmethod
    def sort_by_suit(cards):
        cards.sort(key=lambda card: (card[1], card[0]))

    @staticmethod
    def equal_cards(cards1, cards2, after_sort=True):
        if len(cards1) != len(cards2):
            return False

        if after_sort:
            DeckTestCase.sort_by_suit(cards1)
            DeckTestCase.sort_by_suit(cards2)

        for i, card in enumerate(cards1):
            if card[0] != cards2[i][0] or card[1] != cards2[i][1]:
                return False

        return True

    def test_initializer(self):
        deck = Deck()
        self.assertEqual(52, len(deck.get_cards()))

    def test_print_cards(self):
        cards = DeckTestCase.generate_full_deck()

        _, output = StdoutCapture(
            lambda: self.full_deck.print_cards()).capture()

        self.assertTrue(str(52) in output)
        self.assertTrue(str(cards) in output)

    def test_get_cards(self):
        all_cards = DeckTestCase.generate_full_deck()
        cards = self.full_deck.get_cards()

        self.assertTrue(DeckTestCase.equal_cards(all_cards, cards))

    def test_shuffle(self):
        old_cards = self.full_deck.get_cards().copy()
        self.full_deck.shuffle()

        new_cards = self.full_deck.get_cards()
        self.assertFalse(
            DeckTestCase.equal_cards(old_cards, new_cards, after_sort=False))

    def test_remove_random_card_exists(self):
        cards = self.full_deck.get_cards().copy()
        card = self.full_deck.remove_random_card()

        self.assertTrue(card in cards)
        self.assertFalse(card in self.full_deck.get_cards())

    def test_remove_random_card_nonexistent(self):
        card, output = StdoutCapture(
            lambda: self.empty_deck.remove_random_card()).capture()

        self.assertEqual(card, None)
        self.assertEqual("Deck is empty", output.strip())

    def test_remove_top_card_exists(self):
        cards = self.full_deck.get_cards().copy()
        card = self.full_deck.remove_top_card()

        self.assertEqual(card, cards[0])
        self.assertFalse(card in self.full_deck.get_cards())

    def test_remove_top_card_nonexistent(self):
        card, output = StdoutCapture(
            lambda: self.empty_deck.remove_top_card()).capture()

        self.assertEqual(card, None)
        self.assertEqual("Deck is empty", output.strip())

    def test_remove_card_exists(self):
        target_card = (2, "Spades")
        self.assertTrue(target_card in self.full_deck.get_cards())

        self.full_deck.remove_card(target_card)
        self.assertFalse(target_card in self.full_deck.get_cards())

    def test_remove_card_nonexistent(self):
        card, output = StdoutCapture(lambda: self.empty_deck.remove_card(
            (2, "Spades"))).capture()

        self.assertEqual(card, None)
        self.assertEqual("Deck is empty", output.strip())

    def test_deal(self):
        player1 = Player("p1")
        player2 = Player("p2")

        self.assertEqual(52, len(self.full_deck.get_cards()))
        self.assertEqual(0, len(player1.get_cards()))
        self.assertEqual(0, len(player2.get_cards()))

        self.full_deck.deal([player1, player2], 2)

        self.assertEqual(48, len(self.full_deck.get_cards()))
        self.assertEqual(2, len(player1.get_cards()))
        self.assertEqual(2, len(player2.get_cards()))

    def test_collect(self):
        player1 = Player("p1")
        player2 = Player("p2")

        player1_cards = [(2, "Spades"), (2, "Hearts")]
        player2_cards = [(4, "Hearts")]

        for card in player1_cards:
            player1.add_card(card)

        for card in player2_cards:
            player2.add_card(card)

        self.assertEqual(0, len(self.empty_deck.get_cards()))
        self.assertEqual(2, len(player1.get_cards()))
        self.assertEqual(1, len(player2.get_cards()))

        self.empty_deck.collect([player1, player2])

        self.assertEqual(3, len(self.empty_deck.get_cards()))

        for card in player1_cards:
            self.assertTrue(card in self.empty_deck.get_cards())

        for card in player2_cards:
            self.assertTrue(card in self.empty_deck.get_cards())

    def test_have_all_cards(self):
        full_deck = Deck()

        self.assertTrue(full_deck.have_all_cards())
        full_deck.remove_random_card()
        self.assertFalse(full_deck.have_all_cards())

    def test_push_to_table(self):
        table = Table()

        self.assertEqual(0, len(table.get_cards()))
        self.assertEqual(52, len(self.full_deck.get_cards()))

        self.full_deck.push_to_table(table, 3)

        self.assertEqual(3, len(table.get_cards()))
        self.assertEqual(49, len(self.full_deck.get_cards()))

    def test_print(self):
        _, output = StdoutCapture(lambda: print(self.empty_deck)).capture()
        self.assertEqual("Deck of cards", output.strip())
Exemple #10
0
 def new_game(self):
     deck = Deck()
     self.player_hands = list(deck.deal())
     for i, player in enumerate(self.players):
         player.setIndex(i)
Exemple #11
0
        exit()

    # initialize chips amount
    player = chips()
    print("You have 100 chips")

    while player.amount > 0:
        new_deck = Deck()
        new_deck.shuffle()

        # First turn, place your bets
        bet = player_bet(player.amount)

        # initialize NPC and player Hand
        computer_hand = Hand()
        computer_hand.add_card(new_deck.deal())
        computer_hand.add_card(new_deck.deal())

        player_hand = Hand()
        player_hand.add_card(new_deck.deal())
        player_hand.add_card(new_deck.deal())

        print_hidden_card(player_hand, computer_hand)

        # player turn
        while player_hand.points <= 21:
            chose = input('Hit or stand?\n')
            if chose.lower() == 'hit':
                player_hand.add_card(new_deck.deal())
                player_hand.adjust_for_ace()
class PokerGame:

    # Constructor
    # create instance of a poker game.
    # 2 Players, one human, one AI, 5000 chips each
    def __init__(self, num_players=2):
        self.deck = Deck()
        self.hands = []
        self.community_cards = []
        self.num_players = num_players
        self.pot = 0
        self.bet_amt = 0

    # shuffle function, just shuffles deck
    def shuffle(self):
        self.deck.shuffle()

    # reset the game state for a new hand
    def reset(self):
        self.shuffle()
        self.community_cards = []
        self.hands = []
        self.pot = 0

    # deal in 2 card to all players
    # returns a list of hands
    def dealIn(self):
        for i in range(self.num_players):
            hand = []
            hand.extend(self.deck.deal(2))
            self.hands.append(hand)

        # debug, print hands
#         print(self.getStateStr())

# flop
# deals 3 card to community card

    def flop(self):
        print("Flop!")
        self.community_cards = self.deck.deal(3)

        # debug, print table
        print(self.getStateStr())

    # turn
    # deals 1 card to community card
    def turn(self):
        print("Turn!")
        self.community_cards.extend(self.deck.deal(1))

        # debug, print table
        print(self.getStateStr())

    # river
    # deals 1 card to community card
    def river(self):
        print("River!")
        self.community_cards.extend(self.deck.deal(1))

        # debug, print table
        print(self.getStateStr())

    # assign hand types a label
    def handLabel(self, hand_type):
        if hand_type == 0:
            return "High Card"
        elif hand_type == 1:
            return "Pair"
        elif hand_type == 2:
            return "Two Pair"
        elif hand_type == 3:
            return "Three of a Kind"
        elif hand_type == 4:
            return "Straight"
        elif hand_type == 5:
            return "Flush"
        elif hand_type == 6:
            return "Full House"
        elif hand_type == 7:
            return "Four of a Kind"
        elif hand_type == 8:
            return "Straight Flush"
        else:
            return "Royal Flush"

    # get str representation of hand
    # param: hand is a list with any number of card
    # return a str displaying each card in hand
    def cards2Str(self, hand):
        text = ""
        for c in hand:
            text += str(c) + " "
        return text

    # check if hand has a pair
    # return -1 if no, value of highest pair if yes
    def hasPair(self, hand):
        self.sortHand(hand)
        print(self.cards2Str(hand))
        result = -1
        for c in hand:
            for c2 in hand:
                if c.value == c2.value and c.suit != c2.suit:
                    result = c.value
        return result

    # check if hand has 3 of a kind
    # return -1 if no, value of 3 if yes
    def has3ofKind(self, hand):
        self.sortHand(hand)
        print(self.cards2Str(hand))
        result = -1
        for c in hand:
            num = 0
            for c2 in hand:
                if c2.value == c.value:
                    num += 1
            if num >= 3:
                result = c2.value
        return result

    # sort 7 card hand by card.value
    def sortHand(self, hand):
        hand.sort(key=lambda x: x.value)

    # getStateStr()
    # function prints all values related to current game state
    # returns str representation of state
    def getStateStr(self):
        text = "=== Current Hand State ===\n"
        text += "Community Cards: " + self.cards2Str(
            self.community_cards) + "\n"
        for h in self.hands:
            text += self.cards2Str(h) + "\n"
        text += "Pot: " + str(self.pot) + "\n"
        text += "========================="
        return text

    # score()
    # scores the best 5 card hand given 7 card
    # param: hand to score
    # returns an int between 0 and 9 representing score
    def score(self, hand):
        score = 0
        kicker = []
        # Look for all hand types in hand
        # start with weakest and move up

        # check for pairs first
        pairs = {}
        prev = 0

        # remember how many pairs you have, which pairs
        for card in hand:
            if prev == card.value:
                key = card.value
                if key in pairs:
                    pairs[key] += 1
                else:
                    pairs[key] = 2
            prev = card.value

        # remember number of pairs.
        nop = {}
        for k, v in pairs.items():
            if v in nop:
                nop[v] += 1
            else:
                nop[v] = 1
        # find best possible combination
        if 4 in nop:
            score = 7
            kicker = list(pairs)
            kicker = [key for key in kicker if pairs[key] == 4]
            key = kicker[0]
            #Gets a list of all the card remaining once the the 4 of a kind is removed
            temp = [card.value for card in hand if card.value != key]
            #Get the final card in the list which is the highest card left, used in
            #case of a tie
            card_value = temp.pop()
            kicker.append(card_value)

            return [score, kicker]

        elif 3 in nop:  #Has At least 3 of A Kind
            if nop[3] == 2 or 2 in nop:  #Has two 3 of a kind, or a pair and 3 of a kind (fullhouse)
                score = 6

                #gets a list of all the pairs and reverses it
                kicker = list(pairs)
                kicker.reverse()
                temp = kicker

                #ensures the first kicker is the value of the highest 3 of a king
                kicker = [key for key in kicker if pairs[key] == 3]
                if (
                        len(kicker) > 1
                ):  # if there are two 3 of a kinds, take the higher as the first kicker
                    kicker.pop()  #removes the lower one from the kicker

                #removes the value of the kicker already in the list
                temp.remove(kicker[0])
                #Gets the highest pair or 3 of kind and adds that to the kickers list
                card_value = temp[0]
                kicker.append(card_value)

            else:  #Has Only 3 of A Kind
                score = 3

                kicker = list(pairs)  #Gets the value of the 3 of a king
                key = kicker[0]

                #Gets a list of all the card remaining once the three of a kind is removed
                temp = [card.value for card in hand if card.value != key]
                #Get the 2 last card in the list which are the 2 highest to be used in the
                #event of a tie
                card_value = temp.pop()
                kicker.append(card_value)

                card_value = temp.pop()
                kicker.append(card_value)

        elif 2 in nop:  #Has at Least a Pair
            if nop[2] >= 2:  #Has at least 2  or 3 pairs
                score = 2

                kicker = list(pairs)  #Gets the card value of all the pairs
                kicker.reverse()  #reverses the key so highest pairs are used

                if (len(kicker) == 3
                    ):  #if the user has 3 pairs takes only the highest 2
                    kicker.pop()

                key1 = kicker[0]
                key2 = kicker[1]

                #Gets a list of all the card remaining once the the 2 pairs are removed
                temp = [
                    card.value for card in hand
                    if card.value != key1 and card.value != key2
                ]
                #Gets the last card in the list which is the highest remaining card to be used in
                #the event of a tie
                if len(temp) != 0:
                    card_value = temp.pop()
                else:
                    card_value = 0
                kicker.append(card_value)

            else:  #Has only a pair
                score = 1

                kicker = list(pairs)  #Gets the value of the pair
                key = kicker[0]

                #Gets a list of all the card remaining once pair are removed
                temp = [card.value for card in hand if card.value != key]
                #Gets the last 3 card in the list which are the highest remaining card
                #which will be used in the event of a tie
                card_value = temp.pop()
                kicker.append(card_value)

                card_value = temp.pop()
                kicker.append(card_value)

                card_value = temp.pop()
                kicker.append(card_value)

        # Straight???
        #Doesn't check for the ace low straight
        counter = 0
        high = 0
        straight = False

        #Checks to see if the hand contains an ace, and if so starts checking for the straight
        #using an ace low
        if (hand[6].value == 14):
            prev = 1
        else:
            prev = None

            #Loops through the hand checking for the straight by comparing the current card to the
            #the previous one and tabulates the number of card found in a row
            #***It ignores pairs by skipping over card that are similar to the previous one
        for card in hand:
            if prev and card.value == (prev + 1):
                counter += 1
                if counter == 4:  #A straight has been recognized
                    straight = True
                    high = card.value
            elif prev and prev == card.value:  #ignores pairs when checking for the straight
                pass
            else:
                counter = 0
            prev = card.value

        #If a straight has been realized and the hand has a lower score than a straight
        if (straight or counter >= 4) and score < 4:
            straight = True
            score = 4
            kicker = [
                high
            ]  #Records the highest card value in the straight in the event of a tie

        # Flush???
        flush = False
        total = {}

        #Loops through the hand calculating the number of card of each symbol.
        #The symbol value is the key and for every occurrence the counter is incremented
        for card in hand:
            key = card.suit
            if key in total:
                total[key] += 1
            else:
                total[key] = 1

        #key represents the suit of a flush if it is within the hand
        key = -1
        for k, v in total.items():
            if v >= 5:
                key = int(k)

        #If a flush has been realized and the hand has a lower score than a flush
        if key != -1 and score < 5:
            flush = True
            score = 5
            kicker = [card.value for card in hand if card.suit == key]

        #Straight/Royal Flush???
        if flush and straight:

            #Doesn't check for the ace low straight
            counter = 0
            high = 0
            straight_flush = False

            #Checks to see if the hand contains an ace, and if so starts checking for the straight
            #using an ace low
            if (kicker[len(kicker) - 1] == 14):
                prev = 1
            else:
                prev = None

            #Loops through the hand checking for the straight by comparing the current card to the
            #the previous one and tabulates the number of card found in a row
            #***It ignores pairs by skipping over card that are similar to the previous one
            for card in kicker:
                if prev and card == (prev + 1):
                    counter += 1
                    if counter >= 4:  #A straight has been recognized
                        straight_flush = True
                        high = card
                elif prev and prev == card:  #ignores pairs when checking for the straight
                    pass
                else:
                    counter = 0
                prev = card

            #If a straight has been realized and the hand has a lower score than a straight
            if straight_flush:
                if high == 14:
                    score = 9
                else:
                    score = 8
                kicker = [high]
                return [score, kicker]

        if flush:  #if there is only a flush then determines the kickers
            kicker.reverse()

            #This ensures only the top 5 kickers are selected and not more.
            length = len(kicker) - 5
            for i in range(0, length):
                kicker.pop(
                )  #Pops the last card of the list which is the lowest

        # High Card
        if score == 0:  #If the score is 0 then high card is the best possible hand

            #It will keep track of only the card's value
            kicker = [int(card.value) for card in hand]
            #Reverses the list for easy comparison in the event of a tie
            kicker.reverse()
            #Since the hand is sorted it will pop the two lowest card position 0, 1 of the list
            kicker.pop()
            kicker.pop()
            #The reason we reverse then pop is because lists are inefficient at popping from
            #the beginning of the list, but fast at popping from the end therefore we reverse
            #the list and then pop the last two elements which will be the two lowest card
            #in the hand

        #Return the score, and the kicker to be used in the event of a tie
        return [score, kicker]

    # getWinner()
    # this function calculates the winner of the
    # hand given the current game state.
    # returns the index of the winning player


#     def getWinner(self):

    def scoreHand(self, community_cards, hands):
        for hand in hands:
            hand.extend(community_cards)
            # sort hands
            #             hand.sort(key=lambda x: x.value)
            self.sortHand(hand)

        results = []
        for hand in hands:
            overall = self.score(hand)
            results.append([overall[0], overall[1]])  # store results

        return results

    #determine winner of round
    def findWinner(self, results):
        # show hands TODO: update printing hands with best hand label
        print("Finding Winner...")
        for i in range(len(results)):
            text = ""
            text += self.cards2Str(self.hands[i]) + " " + self.handLabel(
                results[i][0])
            print(text)
        # highest score if found
        high = 0
        for r in results:
            if r[0] > high:
                high = r[0]

            # print(r)

        kicker = {}
        counter = 0
        # kickers only compared if hands are tied (haha, hands are tied)
        for r in results:
            if r[0] == high:
                kicker[counter] = r[1]

            counter += 1

        # if kickers of multiple players are here, there is a tie
        if (len(kicker) > 1):
            print("Tie. Kickers:")
            for k, v in kicker.items():
                print(str(k) + " : " + str(v))
            num_kickers = len(kicker[list(kicker).pop()])
            for i in range(0, num_kickers):
                high = 0
                for k, v in kicker.items():
                    if v[i] > high:
                        high = v[i]

                # only hands with highest kicker matching compared
                kicker = {k: v for k, v in kicker.items() if v[i] == high}
                print("---Round " + str(i) + " ---")
                for k in kicker:
                    print(k)

                # if only one kicker remains they win
                if (len(kicker) <= 1):
                    return list(kicker).pop()

        else:  # one winner found, no kickers needed
            return list(kicker).pop()

        # tie, return list of winners
        return list(kicker)
Exemple #13
0
        answer = input(question)
    return answer


if __name__ == '__main__':

    while True:
        # Print an opening statement
        print('Welcome to play Black Jack! Get as close to 21 as you can without going over!\n\
        Dealer hits until she reaches 17. Aces count as 1 or 11.')

        # Create & shuffle the deck, deal two cards to each player
        deck = Deck()
        deck.shuffle()
        player = Hand()
        player.add_card(deck.deal())
        player.add_card(deck.deal())
        dealer = Hand()
        dealer.add_card(deck.deal())
        dealer.add_card(deck.deal())

        # Set up the Player's chips
        player_chips = player_chips if 'player_chips' in globals() else Chips()

        # Prompt the Player for their bet
        take_bet(player_chips)  # will modify player_chips.bet

        # Show cards (but keep one dealer card hidden)
        show_some(player, dealer)

        while playing:  # recall this variable from our hit_or_stand function
Exemple #14
0
class Round:

    LOGGER = logging.getLogger(name="Round")

    def __init__(self, seats, small_blind, min_denomination):
        self.LOGGER.debug("NEW ROUND")
        self.seats = seats
        self.small_blind = small_blind
        self.min_denomination = min_denomination
        self.cards = []

    def play(self):
        self.shuffle_and_deal()
        self.put_in_blinds()
        starting_bet = self.small_blind * 2
        remaining_seats = self.seats

        first_betting_round = PreFlop(self.seats, remaining_seats, self.cards,
                                      starting_bet)
        remaining_seats = first_betting_round.play()

        if len(remaining_seats) == 1:
            self.distribute_winnings(remaining_seats)
            return self.get_seat_statuses()

        self.deal_flop()
        self.LOGGER.debug("Flop  {}".format(" ".join(
            str(card) for card in self.cards)))

        if self.players_can_bet(remaining_seats):
            second_betting_round = BettingRound(self.seats, remaining_seats,
                                                self.cards)
            remaining_seats = second_betting_round.play()

        if len(remaining_seats) == 1:
            self.distribute_winnings(remaining_seats)
            return self.get_seat_statuses()

        self.deal_turn()
        self.LOGGER.debug("Turn  {}".format(" ".join(
            str(card) for card in self.cards)))

        if self.players_can_bet(remaining_seats):
            third_betting_round = BettingRound(self.seats, remaining_seats,
                                               self.cards)
            remaining_seats = third_betting_round.play()

        if len(remaining_seats) == 1:
            self.distribute_winnings(remaining_seats)
            return self.get_seat_statuses()

        self.deal_river()
        self.LOGGER.debug("River {}".format(" ".join(
            str(card) for card in self.cards)))

        if self.players_can_bet(remaining_seats):
            final_betting_round = BettingRound(self.seats, remaining_seats,
                                               self.cards)
            remaining_seats = final_betting_round.play()

        if len(remaining_seats) == 1:
            self.distribute_winnings(remaining_seats)
            return self.get_seat_statuses()

        winners = self.winners_from_remaining(remaining_seats)

        winner_string = ", ".join(str(winner.index) for winner in winners)
        self.LOGGER.debug("Winning player(s): {}".format(winner_string))

        self.distribute_winnings(winners)

        return self.get_seat_statuses()

    def players_can_bet(self, remaining_seats):
        can_bet = sum(1 for seat in remaining_seats if seat.chips > 0)
        return can_bet > 1

    def get_seat_statuses(self):
        still_in = deque(seat for seat in self.seats if seat.chips > 0)
        gone_out = [seat for seat in self.seats if seat.chips == 0]

        return still_in, gone_out

    def shuffle_and_deal(self):
        self.deck = Deck()
        self.deck.shuffle()

        for seat in self.seats:
            seat.set_card_1(self.deck.deal())

        for seat in self.seats:
            seat.set_card_2(self.deck.deal())

    def put_in_blinds(self):
        small_blind = self.small_blind
        big_blind = self.small_blind * 2

        self.seats[1].bet_chips(small_blind)
        self.seats[2 % len(self.seats)].bet_chips(big_blind)

    def deal_flop(self):
        # burn card
        self.deck.deal()

        # deal three cards as the flop
        for _ in range(3):
            self.cards.append(self.deck.deal())

    def deal_turn(self):
        # burn card
        self.deck.deal()

        # deal turn
        self.cards.append(self.deck.deal())

    def deal_river(self):
        # burn card
        self.deck.deal()

        # deal turn
        self.cards.append(self.deck.deal())

    def winners_from_remaining(self, remaining_seats):
        hands = []

        for seat in remaining_seats:
            hand = get_best_hand(seat.get_cards(), self.cards)
            hands.append((seat, hand))

        best_hand = max(hands, key=lambda seat_hand_pair: seat_hand_pair[1])
        return [
            seat_hand_pair[0] for seat_hand_pair in hands
            if seat_hand_pair[1] == best_hand[1]
        ]

    def distribute_winnings(self, winners):
        winners.sort(key=lambda seat: seat.pot)
        winners_by_deal_order = [
            seat for seat in self.seats if seat in winners
        ]

        while len(winners) > 0:
            winner = winners[0]
            winnings = 0
            winnings_cap = winner.pot

            # create a side pot
            for seat in self.seats:
                winnings += seat.get_chips_from_pot(winnings_cap)

            # split that side pot
            normalized_winnings = winnings // self.min_denomination
            quotient = (normalized_winnings // len(winners)) * \
                self.min_denomination
            remainders = normalized_winnings % len(winners)

            for winner in winners:
                winner.take_winnings(quotient)

            for index in range(remainders):
                winners_by_deal_order[index].take_winnings(
                    self.min_denomination)

            del winners[0]

        for seat in self.seats:
            seat.reclaim_remaining_pot()