【问题标题】:My boolean flag isn't triggering when it's supposed to我的布尔标志没有在它应该触发的时候触发
【发布时间】:2021-05-09 11:22:46
【问题描述】:

在 play_again 输入中,每当我输入“n”结束循环时,python 似乎都会忽略它并打印:

你的牌:[x, x],当前分数:xx 电脑第一卡:x。 你想再抽一张牌吗?按“y”绘画或按“n”站立。

即使我已将 end_game 设置回 True。 什么给了?

import random
from art import logo
from replit import clear
def deal_card():
  cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
  card = random.choice(cards)
  return card

def calculate_score(card_list):
  if len(card_list) == 2 and sum(card_list) == 21:
    return 0
  if 11 in card_list and sum(card_list) > 21:
    card_list.remove(11)
    card_list.append(1)

  return sum(card_list)  

def compare(user, computer):
  if user == computer:
    return "I'ts a draw!"
  elif user == 0:
    return "You win with a BlackJack!"
  elif computer == 0:
    return "Computer wins with a BlackJack!"
  elif computer > 21:
    return "You win! Computer busts."
  elif user > 21:
    return "Computer wins, you bust!"
  elif user > computer:
    return "You win!"
  else:
    return "You lose!"
def main_loop():
  print(logo)
  user_cards = []
  computer_cards = []
  game_end = False

  for _ in range(2):
    user_cards.append(deal_card())
    computer_cards.append(deal_card())

  while not game_end:
    user_score = calculate_score(user_cards)
    computer_score = calculate_score(computer_cards)
    print(f"Your cards: {user_cards}, current score: {user_score}")
    print(f"Computers first card: {computer_cards[0]}.")

    if user_score == 0 or computer_score == 0 or user_score > 21:
      game_end = True
    else:
      play_again = input("Would you like to draw another card? Press 'y' to draw or 'n' to stand.")

      if play_again == "y":
        user_cards.append(deal_card())
      else:
        end_game = True

  while computer_score != 0 and computer_score < 17:
    computer_cards.append(deal_card())
    computer_score = calculate_score(computer_cards)
        
  print(f"Your final hand: {user_cards}, Your final score{user_score}.")
  print(f"Computers final hand: {computer_cards}, Computers final score {computer_score}." )
  print(compare(user_score, computer_score))

while input("Would you like to play a game of BlackJack?: ") == 'y':
  clear()
  main_loop()
else:
  print('Goodbye!')
  quit()

【问题讨论】:

  • 在使用适当的缩进后工作到最后。请更正您的缩进,然后让我们知道发生了什么

标签: python-3.x boolean


【解决方案1】:

请在“while not game_end:”循环中检查你的变量名 game_end,

if user_score == 0 or computer_score == 0 or user_score > 21:
  game_end = True
else:
  play_again = input("Would you like to draw another card? Press 'y' to draw 
                     or 'n' to stand.")

  if play_again == "y":
    user_cards.append(deal_card())
  else:
    end_game = True

我认为它是 "game_end" in else: ,你把 end_game ,请改变它,其他功能正常。

【讨论】:

  • 天哪。是的,这确实解决了它。万分感谢!这真的让我很困惑。
猜你喜欢
  • 2020-09-25
  • 2019-02-13
  • 2010-11-18
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多