Пример #1
0
 def test_kellyCriterion(self):
     deck = BlackjackDeck()
     deck.drawCard()
     self.player.updateCount(
         [Card('2', 'C'), Card('3', 'C'),
          Card('5', 'C')], [Card('Q', 'S')])
     self.assertEquals(self.player.count, 2)
     self.assertEquals(self.player.calculateAdvantage(deck), 0.0125)
     self.assertEquals(self.player.kellyCriterion(deck), 12.5)
Пример #2
0
 def test_mitStrategy(self):
     deck = BlackjackDeck()
     deck.drawCard()
     self.player.updateCount(
         [Card('2', 'C'), Card('3', 'C'),
          Card('5', 'C')], [Card('Q', 'S'), Card('4', 'S')])
     self.player.updateCount(
         [Card('2', 'C'), Card('3', 'C'),
          Card('5', 'C')], [Card('Q', 'S'), Card('4', 'S')])
     self.player.updateCount(
         [Card('2', 'C'), Card('3', 'C'),
          Card('5', 'C')], [Card('Q', 'S'), Card('4', 'S')])
     self.assertEquals(self.player.count, 9)
     self.assertEquals(self.player.mitStrategy(deck), 5)
Пример #3
0
    def __init__(self, numDecks=8, player=Player(), **kwargs):
        self.numDecks = numDecks
        self.deck = BlackjackDeck(self.numDecks)
        # [player, bet]
        self.player = [player, 0]
        self.dealer = Player()
        self.reshuffle = False
        self.learning = False

        if isinstance(self.player[0], QLearningAgent):
            self.learning = True

        # Flags
        self.noPrint = False

        if "flags" in kwargs:
            if "-np" in kwargs['flags']:
                self.noPrint = True
Пример #4
0
    def __init__(self, human = True):
        self.human = human
        self.game_deck = BlackjackDeck()
        self.game_deck.shuffle()
        self.dealer = self.create_dealer('Dealer')
        self.game_counter = 0

        self.PAYOUT = 1.5
        self.DEALER_THRESHOLD = 17
        self.ANTE = 5
Пример #5
0
def test_shuffle():
    deck = BlackjackDeck()
    card = deck.draw_card()
    n.assert_equal(len(deck), 51)
    deck.shuffle()
    n.assert_equal(len(deck), 52)
Пример #6
0
def test_deck_init():
    deck = BlackjackDeck()
    n.assert_equal(len(deck), 52)
    card = deck.draw_card()
    n.assert_equal(card.value_dict['Q'], 10)
Пример #7
0
class Blackjack(object):
    def __init__(self, human = True):
        self.human = human
        self.game_deck = BlackjackDeck()
        self.game_deck.shuffle()
        self.dealer = self.create_dealer('Dealer')
        self.game_counter = 0

        self.PAYOUT = 1.5
        self.DEALER_THRESHOLD = 17
        self.ANTE = 5

    def create_player(self, title):
        if self.human:
            name = raw_input("Enter %s's name: " % title)
        else:
            name = title
        return BlackjackPlayer(name)

    def create_dealer(self, title):
        if self.human:
            name = raw_input("Enter %s's name: " % title)
        else:
            name = title
        return BlackjackPlayer(name, money = 0, is_dealer = True)

    def deal_cards(self,n = 2):
        for _ in xrange(n):
            for player in self.players:
                player.hand.receive_card(self.game_deck.draw_card())
            self.dealer.hand.receive_card(self.game_deck.draw_card())
        for player in self.players:
            print player.hand_str()
        print self.dealer.hand_str(True)

    def actionHit(self, player, action = ''):
        if self.human:
            if action == 'H':
                return True
            elif action == 'S':
                return False
            else:
                player.bet(raw_input("%s Make a bet: $" %player.name))
                player_action = raw_input("%s Hit or Stand? (H/S): " %player.name).upper()
                return self.actionHit(player, player_action)
        else:
            if player.hand.hand_value() > 19:
                player.bet(10)
            elif player.hand.hand_value() < 12 and player.hand.hand_value() > 8:
                player.bet(5)
            return player.hand.hand_value() < self.DEALER_THRESHOLD

    def announce_winners(self, player):
        player.calc_new_wallet_balance(self.PAYOUT)
        print '%s Wallet Balance - $' %player.name  + str(player.wallet)
        if player.won:
            print '%s Congratulations!  You have won this round.' %player.name
        else:
            print 'Dealer won :('
            print 'Sorry... try again?'

    def play_next_round(self):
        all_busted = []
        for player in self.players:
            # Handle all player hits
            while player.hand.hand_value() < 22 and self.actionHit(player):
                player.hand.receive_card(self.game_deck.draw_card())
                print player.hand_str()
                print self.dealer.hand_str(True)

            # did player bust
            if player.hand.hand_value() > 21:
                print 'Player busted...'
                print player.hand_str()
                self.announce_winners(player)
                all_busted.append(True)
            else:
                all_busted.append(False)
            # great score
            if player.hand.hand_value() == 21:
                print 'Congratulations!  You have Blackjack!!!'
                player.won = True
                self.announce_winners(player)

        if all(all_busted):
            return

        while self.dealer.hand.hand_value() < self.DEALER_THRESHOLD:
            self.dealer.hand.receive_card(self.game_deck.draw_card())

        if self.dealer.hand.hand_value() > 21:
            print 'Dealer busted...'
            print self.dealer.hand_str()

        for player in self.players:
            print player.hand_str()
            if player.hand.hand_value() < 21:
                player.won = player.hand >= self.dealer.hand or self.dealer.hand.hand_value() > 21
                self.announce_winners(player)

        print self.dealer.hand_str()

    def howManyPlayers(self):
        if self.human:
            nPlayers = int(raw_input("Enter the number of players (no more than 10):"))
            self.players = [self.create_player('Player %s' %str(i+1)) for i in xrange(nPlayers)] 

    def playAgain(self, action = ''):
        if self.human:
            if action == 'Y':
                return True
            elif action == 'N':
                return False
            else:
                player_action = raw_input("Do you want to play another round (Y/N): ").upper()
                return self.playAgain(player_action)
        else:
            return self.game_counter < 100

    def play_game(self):
        self.howManyPlayers()
        while True:
            for player in self.players:
                player.hand.reset_hand()
                player.won = False
                player.bet(self.ANTE)

            self.dealer.hand.reset_hand()
            self.game_deck.shuffle()
            self.deal_cards()
            self.play_next_round()
            self.game_counter += 1
            if not self.playAgain():
                break
Пример #8
0
class Blackjack:
    def __init__(self, numDecks=8, player=Player(), **kwargs):
        self.numDecks = numDecks
        self.deck = BlackjackDeck(self.numDecks)
        # [player, bet]
        self.player = [player, 0]
        self.dealer = Player()
        self.reshuffle = False
        self.learning = False

        if isinstance(self.player[0], QLearningAgent):
            self.learning = True

        # Flags
        self.noPrint = False

        if "flags" in kwargs:
            if "-np" in kwargs['flags']:
                self.noPrint = True

    # Deals a card to player from the deck
    # If card dealt is cut card, plan to reshuffle at end of round
    def dealCard(self, player):
        card = self.deck.drawCard()
        if card.getValue() == "cut":
            self.reshuffle = True
            card = self.deck.drawCard()
        player.addToHand(card)

    def double(self, player):
        self.dealCard(player[0])
        player[1] = player[1] * 2
        player[0].doubleBet()

    # Deals cards to start a round
    def startRound(self):
        for _ in xrange(2):
            self.dealCard(self.player[0])
            self.dealCard(self.dealer)
        if self.learning:
            # initialize state for Q-Learning
            self.player[0].updateState(
                (self.player[0].getHandValue(),
                 self.dealer.getCardValue(self.getDealerUpcard())))

    # Gets the dealer's face up card (i.e. first card in hand)
    def getDealerUpcard(self):
        return self.dealer.getHand()[0]

    # Runs the game
    def playRound(self):
        self.startRound()

        # Gather bet
        bet = self.player[0].getBet(self.deck)
        if bet == False:
            return (False, self.player[0].winRate)
        self.player[1] = bet

        # Get dealer's face up card
        dealerUpcard = self.getDealerUpcard()
        lastAction = None
        lastState = None

        # Player turn
        while True:
            if not self.noPrint:
                print "\n\nDealer upcard: {0}".format(dealerUpcard)

            # Value of dealer's face-up card for qlearning
            dealerUpValue = self.dealer.getCardValue(dealerUpcard)

            # getAction determines next action according to agent
            action = self.player[0].getAction(dealerUpcard)

            lastState = self.player[0].getHandValue(), dealerUpValue

            if action == "bust":
                break
            if action == "stand":
                lastAction = 2
                break
            elif action == "hit":
                lastAction = 1
                self.dealCard(self.player[0])
                # Update Q-Values
                if self.learning:
                    self.player[0].update(
                        lastState, 1,
                        (self.player[0].getHandValue(), dealerUpValue), None)
            elif action == "double":
                lastAction = 3
                self.double(self.player)
                # Update Q-Values
                if self.learning:
                    self.player[0].update(
                        lastState, 3,
                        (self.player[0].getHandValue(), dealerUpValue), None)
                break

        # Dealer actions
        while True:
            # Don't care about hard vs. soft values
            dealerValue = self.dealer.getHandValue()[0]
            dealerBlackjack = True if dealerValue == const.blackjack else False

            if not self.noPrint:
                print "\n"
                print "Dealer hand: " + " ".join(
                    [str(card) for card in self.dealer.getHand()])
                print "Dealer hand value: {0}".format(dealerValue)
                if dealerValue == const.blackjack:
                    print "Dealer has BLACKJACK"
                elif dealerValue > 21:
                    print "Dealer BUST"
                elif dealerValue >= 17:
                    print "Dealer STANDS on {0}".format(dealerValue)
                else:
                    print "Dealer HITS"

            # Dealer stands on 17 (stand on soft 17)
            if dealerValue == const.blackjack or dealerValue >= 17:
                break

            # Else hit
            self.dealCard(self.dealer)

        # Determine winnings
        playerValue = self.player[0].getHandValue()[0]
        playerBlackjack = True if playerValue == const.blackjack else False

        if not self.noPrint:
            print "\n"

        if playerValue == const.blackjack and dealerValue == const.blackjack:
            payout = self.player[1]
        elif playerValue == const.blackjack:
            payout = 5 * self.player[1] / 2
        elif dealerValue == const.blackjack or playerValue > 21:
            payout = 0
        elif dealerValue > 21 or playerValue > dealerValue:
            payout = 2 * self.player[1]
        elif playerValue == dealerValue:
            payout = self.player[1]
        else:
            payout = 0
        self.player[0].addMoney(payout)

        if not self.noPrint:
            if playerValue == const.blackjack and dealerValue == const.blackjack:
                print "Dealer got BLACKJACK and you got BLACKJACK\nPUSH"
            elif playerValue == const.blackjack:
                print "You got BLACKJACK\nYou win ${0}".format(
                    3 * self.player[1] / 2)
            elif dealerValue == const.blackjack:
                print "Dealer got BLACKJACK\nYou lose ${0}".format(
                    self.player[1])
            elif playerValue > 21:
                print "You BUST\nYou lose ${0}".format(self.player[1])
            elif dealerValue > 21:
                print "Dealer BUSTS\nYou win ${0}".format(self.player[1])
            elif playerValue > dealerValue:
                print "Dealer has value {0} and you have value {1}\nYou win ${2}".format(
                    dealerValue, playerValue, self.player[1])
            elif playerValue == dealerValue:
                print "Dealer has value {0} and you have value {1}\nPUSH".format(
                    dealerValue, playerValue)
            else:
                print "Dealer has value {0} and you have value {1}\nYou lose ${2}".format(
                    dealerValue, playerValue, self.player[1])

        reward = payout - self.player[1]
        result = self.player[0].roundEnd(reward, self.player[0].getHand(),
                                         self.dealer.getHand())
        if self.learning:
            self.player[0].update(
                lastState, lastAction,
                (self.player[0].getHandValue(), dealerUpValue), reward)

        # Clear cards
        self.player[0].discardHand()
        self.dealer.discardHand()

        # Reshuffle if needed:
        if self.reshuffle:
            if not self.noPrint: print "\n\nReshuffling!"
            self.deck.reshuffle()
            self.player[0].reshuffled()
            self.reshuffle = False

        return (True, 0)
Пример #9
0
def test_shuffle():
    deck = BlackjackDeck()
    card = deck.draw_card()
    n.assert_equal(len(deck), 51)
    deck.shuffle()
    n.assert_equal(len(deck), 52)
Пример #10
0
def test_deck_init():
    deck = BlackjackDeck()
    n.assert_equal(len(deck), 52)
    card = deck.draw_card()
    n.assert_equal(card.value_dict['Q'], 10)