Python小游戏代码无法返回商店菜单,求助帮忙修复代码问题
Python小游戏商店功能修复方案
原代码核心问题
- 缩进错误:Python依赖缩进划分代码块,原代码中while循环、条件判断的从属代码未正确缩进,逻辑无法按预期执行
- 循环条件逻辑错误:原代码定义
Shop = ["Shop"],将response not in Shop作为循环条件,用户输入的yes/no永远无法匹配该值,循环逻辑完全失效 - 语法错误:长字符串跨行未做拼接处理,直接运行会触发报错
- 金币计算逻辑错误:每次购买硬编码从1000扣除,未读取当前
Coins变量的实际值,多次购买时数值计算错误 - 分支逻辑错误:判断用户输入no的分支被错误缩进在购买逻辑内,永远无法被触发
- 缺少回到商店菜单的循环逻辑:购买完成后没有跳转回商品选择页面的对应处理
修复后完整代码
import time CharacterHealth = 100 Coins = 1000 Sword = ["Diamond", "Metal", "Wood"] 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") print("\033[1;37;40mHello, " + name + ". Would you like to enter a shop?\nYou can purchase swords!\n") time.sleep(2) while True: # 外层循环:询问是否进入商店 response = input("\033[1;37;40mWould you like to enter the shop?(yes/no)\nSelection: \033[1;32;40m").lower() if response == "yes": # 内层循环:商店商品菜单,操作完成后自动回到该菜单 while True: answer = input(f"\n\033[1;37;40mYou have {Coins} 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").lower() if answer == "a": if Coins >= 900: Coins -= 900 input(f"{name}\033[1;37;40m, you currently have {Coins} Coins! Press any key to return to shop menu.") else: input(f"{name}\033[1;37;40m, your coins are not enough! Press any key to return to shop menu.") elif answer == "b": if Coins >= 500: Coins -= 500 input(f"{name}\033[1;37;40m, you currently have {Coins} Coins! Press any key to return to shop menu.") else: input(f"{name}\033[1;37;40m, your coins are not enough! Press any key to return to shop menu.") elif answer == "c": if Coins >= 200: Coins -= 200 input(f"{name}\033[1;37;40m, you currently have {Coins} Coins! Press any key to return to shop menu.") else: input(f"{name}\033[1;37;40m, your coins are not enough! Press any key to return to shop menu.") elif answer == "d": print("You exit the shop.\n") time.sleep(2) # 退出内层循环,回到外层是否进入商店的询问 break elif response == "no": print("You exit the shop.") print("You enter your house.") # 退出外层循环,结束流程 break else: print("Invalid input, please enter yes or no.")
效果说明
- 购买任意商品完成后,按下任意键会自动回到商店商品选择菜单
- 新增金币不足校验,避免出现负金币的异常情况
- 所有输入统一转为小写判断,无需区分大小写输入
- 选择d退出商店后,会回到是否进入商店的询问,选择no即可退出商店进入房屋流程
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

