예제 #1
0
class BlackJackSimulation(object):
    def __init__(self):
        self.the_doctor = Player("The Doctor")
        self.the_master = Player("The Master")
        self.dealer = Player("Dealer")
        self.game = BlackJack([self.the_doctor, self.the_master], self.dealer)

    def play(self):
        print ("Starting Blackjack")
        self.game.start()
        # start off by calculating the value of the players' cards
        self.calculate_hand(self.dealer)

        for player in self.game.players:
            self.calculate_hand(player)

        # for the sake of testing, we'll loop for 5 rounds
        for x in xrange(5):
            dealer_score = self.game.get_points_for_player(self.dealer)

            if dealer_score <= 15:
                self.game.hit(self.dealer)
                self.calculate_hand(self.dealer)  # reprocess the card values

            for player in self.game.players:
                if self.game.get_points_for_player(player) <= 15:
                    self.game.hit(player)
                    self.calculate_hand(player)  # reprocess the card values

        # Show final hand
        print (
            "{0}\t\t{1}\t{2}".format(
                self.dealer.name, self.game.get_points_for_player(self.dealer), self.dealer.printable_hand()
            )
        )

        for player in self.game.players:
            print (
                "{0}\t{1}\t{2}".format(player.name, self.game.get_points_for_player(player), player.printable_hand())
            )

        print ("*" * 45)

    def calculate_hand(self, player):
        """ A helper function to assist the bot in knowing when to hit
            by selecting the value of aces
        """
        total = sum([self.game.get_point_values(card) for card in player.hand if card.value != "A"])

        aces = [card for card in player.hand if card.value == "A"]

        # this is a crude method, this is NOT supposed to be a fully functioning
        # game. Just a rough demo of the code to create a game.
        def handle_aces(total, aces):
            ace_count = len(aces)

            if total <= 11 - ace_count:
                if ace_count:
                    # set the first ace to 11, the rest to 1
                    self.game.set_point_value(aces[0], 11)
                    [self.game.set_point_value(card, 1) for card in aces[1:]]

                return total + 10 + ace_count
            else:
                if ace_count:
                    [self.game.set_point_value(card, 1) for card in aces]
                return total + ace_count

        total = handle_aces(total, aces)

        return total