为什么加法函数不能正常工作



我正在尝试制作21点游戏,但添加功能似乎不起作用,因为我想要它,我不知道为什么。总值有时比实际值大。

import random
cards = ["ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] user_hand = []
dealer_hand = [] hit_stand = "h" bust = False
def card_addition(hand, total):
# return sum(hand)
for n in hand:
if n == "ace" and total <= 10:
total += 11
elif n == "ace" and total >= 11:
total += 1
else:
total += n
for n in hand:
if n == "ace" and total > 21:
total -= 10
return total

for card in range(2):
user_hand.append(random.choice(cards))
for card in range(1):
dealer_hand.append(random.choice(cards))
dealer_hand.append("hidden")
def hit(hand):
hand.append(random.choice(cards))
user_total = 0
print (f"Your hand is {user_hand}") print (f"Dealer's hand is
{dealer_hand}")  
while user_total < 21 and hit_stand == "h":
hit_stand = input("Hit or stand ? (h/s)")
if hit_stand == "h":
hit(user_hand)
user_total = card_addition(user_hand, user_total)
print(f"Your hand is {user_hand} and your total is {user_total}.")
elif hit == "s":
print("STAND !") if user_total > 21:
bust = True

dealer_hand.remove("hidden") dealer_hand.append(random.choice(cards))
dealer_total = 0 dealer_total = card_addition(dealer_hand,
dealer_total)

while dealer_total < 16 and bust == False:
hit(dealer_hand)
dealer_total = card_addition(dealer_hand, dealer_total) print(f"Dealer hand is {dealer_hand} and the total is
{dealer_total}.")
if user_total > dealer_total and bust == False:
print("You win !") elif dealer_total > user_total and bust == False:
print("Dealer wins !") elif dealer_total == user_total and bust == False:
print("Draw !")
if bust == True:
print("BUST !")

,输出祝辞的在

Your hand is ['ace', 2]
Dealer's hand is [9, 'hidden']
Hit or stand ? (h/s)h
Your hand is ['ace', 2, 10] and your total is 13. 
Hit or stand ? (h/s)h
Your hand is ['ace', 2, 10, 8] and your total is 24. 
Dealer hand is [9, 8] and the total is 17. 
BUST !

删除user_totaldealer_total为我做到了。只需调用print()内部的函数。

if hit_stand == "h":
hit(user_hand)
print(f"Your hand is {user_hand} and your total is {card_addition(user_hand, user_total)}.")

最新更新