【发布时间】:2017-03-18 13:49:34
【问题描述】:
我正在用 python 编写二十一点代码。到目前为止,我已经为玩家处理了两张初始牌。如果是自然获胜,程序会识别它并打印“BlackJack!”。如果有可能命中,则会提示用户“命中还是站立?H\S。我无法弄清楚如何将“命中”卡的值添加到前两张卡的值中。
这是我的代码:
import random
def create_hand(hand):
for i in range(2):
pip = random.choice(PIPS)
suit = random.choice(SUITS)
card = (pip,suit)
player_hand.append(card)
def print_hand(hand):
for pip, suit in hand:
print(pip + suit,end=" ")
print()
def sum_hand(hand):
total = 0
for pip,suit in player_hand:
if pip == "J" or pip == "Q" or pip == "K":
total += 10
elif pip == "A" and total < 10:
total += 11
elif pip == "A" and total == 10:
total +=11
elif pip == "A" and total > 10:
total += 1
else:
total += int(pip)
if total == 21:
print("BlackJack!")
return total
def hit_card():
pip = random.choice(PIPS)
suit = random.choice(SUITS)
card = (pip, suit)
return card
def hit(player_hand):
total = sum_hand(player_hand)
choice = input("Hit or Stand? h/s: ")
while choice.lower() == "h":
if total != 21:
player_hand.append(hit_card())
print_hand(player_hand)
CLUB = "\u2663"
HEART = "\u2665"
DIAMOND = "\u2666"
SPADE = "\u2660"
PIPS = ("A","2","3","4","5","6","7","8","9","10","J","Q","K")
SUITS = (CLUB, SPADE, DIAMOND, HEART)
player_hand = []
total = sum_hand(player_hand)
create_hand(player_hand)
print_hand(player_hand)
hit(player_hand)
【问题讨论】: