Python游戏中If/Elif/Else语句无法按预期退出游戏问题
Higher or Lower游戏重玩退出异常修复
问题现象
- 首次游戏后输入“no”,可正常退出并显示退出图片
- 选择“yes”重玩后,再次输入“no”无法直接退出,需多次输入才能完全结束游戏
问题原因
当前代码使用递归调用main_game()处理重玩请求,但递归调用完成后会回到上一层函数的while True循环,继续触发重玩询问。每重玩一次就会新增一层递归栈,输入“no”仅能退出当前递归层,回到上一层的询问循环,因此需要多次输入才能退出所有递归层级。
修复方案
方案1:修改递归逻辑(最小改动)
在递归调用main_game()后立即返回当前函数,避免回到上一层的询问循环。修改重玩判断部分的代码:
while True: play_again = input("\nDo you want to play again? (yes or no): ") play_again = play_again.lower() if play_again == "yes": # 递归调用后直接返回,终止当前函数的循环 return main_game(user_score, playing_again=True, option_3=option2) elif play_again == "no": return 0 else: print("You have not entered 'yes' or 'no'. Please try again.")
方案2:改用迭代循环(更推荐)
重构代码为迭代结构,彻底避免递归栈问题,同时让逻辑更直观:
import art import gameData import random def main_game(): user_score = 0 playing_again = False prev_option = "" while True: # 选择对比选项 if playing_again: option_a = prev_option option_b = gameData.data[random.randint(1, 50)] else: # 生成不重复的随机索引 idx1 = random.randint(1, 50) idx2 = random.randint(1, 50) while idx1 == idx2: idx2 = random.randint(1, 50) option_a = gameData.data[idx1] option_b = gameData.data[idx2] # 提取选项信息(直接用字典键访问,更简洁) print(f"\nCompare A: {option_a['name']}, a {option_a['description']}, from {option_a['country']}.") print(art.vs_image) print(f"Against B: {option_b['name']}, a {option_b['description']}, from {option_b['country']}.") # 获取有效用户输入 while True: user_guess = input("\nWho has more followers? Type 'A' or 'B': ").upper() if user_guess in ("A", "B"): break print("You can only enter 'A' or 'B'. Please try again.") # 判断答案正确性 correct_answer = "A" if option_a["follower_count"] > option_b["follower_count"] else "B" if user_guess == correct_answer: print("\nWell done you were correct!") user_score += 1 print(f"Your score is now {user_score}") playing_again = True prev_option = option_b # 保留当前B选项作为下一轮的A选项 else: print("\nYou got it wrong!") playing_again = False # 重玩询问 while True: play_again = input("\nDo you want to play again? (yes or no): ").lower() if play_again == "yes": break elif play_again == "no": return 0 else: print("You have not entered 'yes' or 'no'. Please try again.") # 启动游戏 print(art.starting_image) print("Welcome to the higher or lower game!") print("\nGame Rules: From the 2 options shown you have to pick which celebrity or brand has more Instagram followers.") status = main_game() if status == 0: print(art.exit_image)
方案2优化点说明
- 用内部
while True循环替代递归,彻底解决多层递归导致的退出问题 - 直接通过字典键(如
option_a['name'])提取数据,比list(option1.items())[0][1]更简洁易读 - 重玩逻辑通过标志位和变量传递实现,代码结构更清晰
内容的提问来源于stack exchange,提问作者Keith Colclough
相关产品推荐
相关产品推荐

