开发Python老虎机游戏遇金额无法持久化保存问题求助
老虎机游戏金额保存问题修复方案
你的核心问题是每次用户选择重新玩时,递归调用了main()函数,这会让函数重新执行所有初始化代码,包括Money = 100,导致之前的余额被重置。另外代码里的Roll()函数没有实现,运行会报错,也需要补上。
修复后的完整代码
# Slot machine import random import time def Roll(SlotMachine, Slot1, Slot2, Slot3): # 清空之前的结果 Slot1.clear() Slot2.clear() Slot3.clear() # 模拟老虎机滚动 for _ in range(3): Slot1.append(random.choice(SlotMachine)) Slot2.append(random.choice(SlotMachine)) Slot3.append(random.choice(SlotMachine)) # 打印滚动结果 print(f"[{Slot1[0]}] [{Slot2[0]}] [{Slot3[0]}]") def main(): # 初始金额只初始化一次 Money = 100 SlotMachine = ["Strawberry", "Apple", "Banana"] Slot1 = [] Slot2 = [] Slot3 = [] play_again = True while play_again and Money > 0: print("If you lose, you'll lose all the money you put on the line. But if you win your money gets tripled!") MoneyOnTheLine = int(input("How much money would you like to put on the table? ")) if MoneyOnTheLine < 0: print("Invalid amount, try again.") continue if MoneyOnTheLine > Money: print("You don't have that kind of money...") continue Money -= MoneyOnTheLine Roll(SlotMachine, Slot1, Slot2, Slot3) if Slot1 == Slot2 == Slot3: print("You win!") WinnersMoney = MoneyOnTheLine * 3 print(f"You received {WinnersMoney}!") Money += WinnersMoney print(f"You have {Money} now!") Restart = input("Good job, you won! Wanna play again? (Yes/No) ").lower() else: print(f"You have {Money} now!") Restart = input("It seems you lost, wanna play again? (Yes/No) ").lower() # 根据用户选择设置是否继续,不再递归调用main() if Restart != "yes": play_again = False print("I'll see you another time, friend!") if Money <= 0: print("You are poor!") if __name__ == "__main__": main()
关键修改说明
- 移除了递归调用
main()的逻辑,改用play_again标志位控制循环,确保Money不会被重新初始化 - 实现了
Roll()函数,完成老虎机滚动的核心逻辑,传入需要操作的列表参数 - 优化了输入校验的提示信息,让用户更清楚错误原因
- 调整了字符串格式化,用更简洁的f-string语法
- 添加了
if __name__ == "__main__":规范,符合Python代码最佳实践
这样修改后,用户每次选择继续玩时,余额会被保留,不会重置为初始的100。
内容的提问来源于stack exchange,提问作者Zenofort
相关产品推荐
相关产品推荐

