为什么我的 while 循环在满足其中一个条件时没有结束?



我正在构建一个基本的21点游戏,我已经做了一个while循环,一旦玩家手牌或房屋手牌大于21,它就会终止,但它只是不断循环?

疯狂的是,我确实让它工作过一次,但在测试另一个我试图工作的函数时,我不小心又把它弄坏了(如果大于21,就把11变成1(,我似乎无法让它再次工作?

import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
player_hand = []
house_hand = []
def player_opening_hand():
for hand in range (0,2):
player_hand.append(random.choice(cards))
def house_opening_hand():
for hand in range(0,2):
house_hand.append(random.choice(cards))
def total_score(hand):
return sum(hand)
def new_draw(draw):
draw.append(random.choice(cards))
# if total_score(draw) > 21 and 11 in draw:
#     draw[11] = 1
def current_score():
print(f'Your cards: {player_hand}, total score: {total_score(player_hand)}')
print(f"computer's first card: {house_hand[0]}")
def final_score():
print(f'Your cards: {player_hand}, total score: {total_score(player_hand)}')
print(f"computer's cards: {house_hand}, house total score: {total_score(house_hand)}")

#Intro to the player
begin = input('welcome to pyjack, would you like to start a new game? enter "y" or "n": ')


if begin == 'y':
# first two cards for both players are dealt,
player_opening_hand()
house_opening_hand()
current_score()
if total_score(player_hand) == 21:
print('you won!')
else:
while total_score(player_hand) and total_score(house_hand) < 21:
player_choice = input('Type "y" to get another draw or type "n" to pass: ')
if player_choice == 'y':
new_draw(player_hand)
current_score()
if total_score(player_hand) > 21:
final_score()
print('you went over 21, you lose!')
elif total_score(player_hand) > total_score(house_hand):
final_score()
print('your hand is bigger than the house! you win!')
elif total_score(player_hand) == 21 and total_score(house_hand) < 21:
final_score()
print('Blackjack! you win!')
else:
final_score()
print('you lose!')

您总是必须使用ANDOR运算符来提及这两个条件。这里的条件是:

while total_score(player_hand) < 21 and total_score(house_hand) < 21:

我希望这对你有用。

while total_score(player_hand) and total_score(house_hand) < 21:

并没有做你认为它会做的事。正确的代码是

while total_score(player_hand) < 21 and total_score(house_hand) < 21:

最新更新