Python游戏代码break异常终止问题求助:如何让循环跳出后执行后续代码
问题解决方法
问题根源
你代码中的else块是和最外层判断是否进入商店的if配对的,仅当用户选择不进入商店(输入no/No)时才会执行。当用户选择进入商店后,所有操作都在if分支内部完成,break只是跳出内部的while循环,自然不会触发外层的else代码,所以程序直接结束。
修复方案
要实现「买完剑或者手动退出商店后都执行退出提示+回家逻辑」,只需把else块里的公共代码挪到合适的位置即可,同时同步修复了代码中存在的其他小问题:
- 初始化
Sword的or逻辑无效问题 - 购买木剑时未给
Sword赋值导致打印错误的问题 - 输入提示中转义码带空格导致颜色失效的问题
修复后完整代码
import time def coins_left(player_name, coins): print(player_name + "\033[1;37;40m, you currently have " + str(coins) + " Coins!") CharacterHealth = 100 Coins = 1000 Sword = None Shop = ["Shop"] print("Hello! Welcome to my game! This is an extremely fun action game! I hope you enjoy!\n") time.sleep(2) name = input("Please enter your username.\nUsername: \033[1;32;40m") response = input("\033[1;37;40mHello, " + name + ". Would you like to enter the shop?(yes/no)\nSelection: \033[1;32;40m") if (response == "Yes") or (response == "yes"): while True: answer = input("\n\033[1;37;40mYou have %s coins. Would you like to buy:\n(a) Diamond sword [Costs 900]\n(b) Metal Sword[500]\n(c) Wooden sword[200]\n(d) Back\nSelection: \033[1;32;40m" % Coins) if (answer == "A") or (answer == "a"): Sword = "Diamond" print(name + ", you have bought a " + str(Sword) + " Sword!") Coins -= 900 coins_left(name, Coins) break elif (answer == "B") or (answer == "b"): Sword = "Metal" print(name + ", you have bought a " + str(Sword) + " Sword!") Coins -= 500 coins_left(name, Coins) break elif (answer == "C") or (answer == "c"): Sword = "Wooden" print(name + ", you have bought a " + str(Sword) + " Sword!") Coins -= 200 coins_left(name, Coins) break elif (answer == "D") or (answer == "d"): print("You exit the shop.\n") break # 公共逻辑统一放在末尾,无论是否进入商店都会执行 print("\033[1;37;40mYou exit the shop.") print("After leaving the shop, you head home.")
内容的提问来源于stack exchange,提问作者user16800899
相关产品推荐
相关产品推荐

