官术网_书友最值得收藏!

The Hand class

A Hand class will need to contain cards just like the Deck class does. It will also be assigned a value by the rules of the game based on which cards it contains.

Since the dealer's hand should only display one card, we also keep track of whether the Hand belongs to the dealer to accommodate this rule: 

class Hand:
def __init__(self, dealer=False):
self.dealer = dealer
self.cards = []
self.value = 0

def add_card(self, card):
self.cards.append(card)

Much like the Deck, a Hand will hold its cards as a list of Card instances.

When adding a card to the hand, we simply add the Card instance to our cards list.

Calculating the value of a Hand is where the rules of the game come into play the most:

def calculate_value(self):
self.value = 0
has_ace = False
for card in self.cards:
if card.value.isnumeric():
self.value += int(card.value)
else:
if card.value == "A":
has_ace = True
self.value += 11
else:
self.value += 10

if has_ace and self.value > 21:
self.value -= 10

def get_value(self):
self.calculate_value()
return self.value

We first initialize the value of the hand to 0 and assume the player does not have an ace (since these are a special case). We then loop through the Card instances and try to add their value as a number to the player's total.

If the card's value is not numerical, we will then check to see whether the card is an ace. If it is, we begin by adding 11 to the hand's value and setting the has_ace flag to True. If this increase of 11 points brings the hand's value over 21, we make the ace worth 1 point instead, and so subtract 10 from the hand's value.

If the card is not numerical or an ace, we simply add 10 to the hand's value.

We need some way for the game to display each hand's cards, so we use a simple function to print each card in the hand, and the value of the player's hand too. The dealer's first card is face down, so we print hidden instead:

def display(self):
if self.dealer:
print("hidden")
print(self.cards[1])
else:
for card in self.cards:
print(card)
print("Value:", self.get_value())

Now that we have all of our underlying data structures written, it's time for the game loop. This will be contained in a Game class for simplicity's sake.

主站蜘蛛池模板: 建瓯市| 阳山县| 雅安市| 峡江县| 蒲江县| 阿图什市| 合阳县| 临漳县| 兴业县| 牟定县| 英德市| 霞浦县| 泰和县| 苏尼特左旗| 古丈县| 嫩江县| 井陉县| 潍坊市| 东海县| 宜良县| 南江县| 贡山| 泾源县| 淮阳县| 洱源县| 开远市| 宝兴县| 孙吴县| 哈尔滨市| 肇东市| 习水县| 临夏县| 博罗县| 化德县| 浦北县| 新巴尔虎左旗| 绍兴县| 自治县| 德江县| 沛县| 鄂托克旗|