Python老虎机游戏重复游玩功能实现问题求助
老虎机游戏重复游玩功能问题修复
我正在开发一个老虎机个人项目,想实现用户输入是否再次游玩的重复功能,但循环逻辑搞不定。我写了个叫repeat的函数:
def repeat(Money): Win(Money) print(WinCheckValue, Money) playagain(Money) repeat(Money)
但这个函数只会递归调用自己和playagain,其他必要的函数没跑起来。下面是完整的Python代码:
import random Money = 10 def SlotRoller(number1, number2): return random.randint(number1, number2) slot1 = SlotRoller(1, 3) slot2 = SlotRoller(1, 3) slot3 = SlotRoller(1, 3) match slot1: case 1: slot1 = "cherry" case 2: slot1 = "grape" case 3: slot1 = "orange" match slot2: case 1: slot2 = "cherry" case 2: slot2 = "grape" case 3: slot2 = "orange" match slot3: case 1: slot3 = "cherry" case 2: slot3 = "grape" case 3: slot3 = "orange" WinCheckValue = [slot1, slot2, slot3] def Win(Money): Money = Money - 1 match WinCheckValue: case ["orange", "orange", "orange"]: print("!Big Win!") Money+=25 return Money case ["grape", "grape", "grape"]: print("!Big Win!") Money+=25 return Money case ["cherry", "cherry", "cherry"]: print("!Big Win!") Money+=25 return Money playagain(Money) def playagain(Money): n = input("Would you like to play again? (y/n)") if n == "y": Win(Money) else: print("Ok") def repeat(Money): Win(Money) print(WinCheckValue, Money) playagain(Money) repeat(Money) repeat(Money)
问题分析
- 摇奖结果固定不变:slot1、slot2、slot3和WinCheckValue在程序启动时就生成完毕,后续重复游玩不会重新摇奖,导致每次结果完全一致。
- 递归逻辑混乱:
repeat函数无终止递归,不仅会触发栈溢出,还跳过了重新生成摇奖结果的核心流程。 - 余额传递失效:
Win函数只有中奖时才返回更新后的余额,未中奖时直接调用playagain,导致余额的更新无法传递到后续流程。 - 全局变量滥用:全局变量的状态没有在每轮游玩后重置,导致游戏状态混乱。
修复后的代码
import random def slot_roller(): # 生成单个滚轮的随机结果并转换为水果 num = random.randint(1, 3) match num: case 1: return "cherry" case 2: return "grape" case 3: return "orange" def play_round(money): # 扣除单次游玩成本 money -= 1 # 重新生成三个滚轮的结果 slot1 = slot_roller() slot2 = slot_roller() slot3 = slot_roller() win_check = [slot1, slot2, slot3] print(f"滚轮结果: {win_check}") # 判断是否中大奖 if slot1 == slot2 == slot3: print("!Big Win!") money += 25 return money, win_check def main(): money = 10 while True: # 执行一轮游戏 money, result = play_round(money) print(f"当前余额: {money}") # 询问用户是否继续游玩 choice = input("要不要再玩一次?(y/n): ").lower().strip() if choice != "y": print("游戏结束") break if __name__ == "__main__": main()
关键改动说明
- 封装摇奖逻辑:将生成滚轮结果的代码封装为
slot_roller函数,每次游玩都重新调用,保证结果随机。 - 用while循环替代递归:
main函数中的while True循环实现重复游玩,逻辑清晰且不会出现栈溢出问题。 - 统一状态管理:通过函数返回值传递更新后的余额和滚轮结果,避免全局变量导致的状态混乱。
- 完善流程控制:每轮游玩结束后统一询问是否继续,确保所有流程按顺序执行,没有逻辑遗漏。
内容的提问来源于stack exchange,提问作者Bad Coder
相关产品推荐
相关产品推荐

