Python水果老虎机开发:数组抽随机串及高效判断中奖条件
水果老虎机代码优化与问题解决
问题拆解
你当前的代码存在三个核心问题:
- 重复元素判断依赖冗余的if/elif,效率低且扩展性差
- credits归0后循环未及时终止,导致扣除后出现负数
- 函数间参数传递错误,中奖后的credits修改无法同步到主逻辑
针对性解决方案
1. 高效判断中奖条件
用collections.Counter统计元素出现次数,替代大量条件判断,逻辑更清晰:
- 统计抽中元素的频次,快速判断是否符合中奖规则
- 优先处理扣分规则(抽到Skull),再判断中奖情况
2. 修复credits负数问题
- 在扣除credits前先检查余额是否足够,避免超额扣除
- 确保函数间的credits状态同步,通过返回值更新主逻辑中的credits
- 调整循环终止条件,当credits不足2时直接提示无法继续
3. 代码整体优化
- 移除无用的
end()函数,直接处理结束逻辑 - 打印每次抽中的结果,提升交互体验
- 简化输入校验逻辑,确保输入有效
优化后的完整代码
import random from collections import Counter fruit = ["Cherry", "Bell", "Lemon", "Star", "Orange", "Skull"] def fruit_machine(): credits = 10 while credits >= 2: turn = input("Would you like to roll for 20p? Y/N: ").strip().lower() if turn == "y": credits -= 2 print(f"You have {credits} credits remaining") # 执行抽奖并更新credits credits = fruit_roll(credits) elif turn == "n": print("You have chosen not to roll.") break else: print("Please enter a valid option (Y/N).") # 循环结束后提示余额 print(f"--------------------------------------\nYou have {credits} credits remaining") if credits == 0: print("Game over - no more credits left!") return credits def fruit_roll(credits): roll = random.choices(fruit, k=3) print(f"You rolled: {', '.join(roll)}") counts = Counter(roll) # 处理扣分规则:抽到Skull skull_count = counts.get("Skull", 0) if skull_count > 0: credits -= skull_count * 1 # 每个Skull扣1分,可根据需求调整 print(f"Oops! You got {skull_count} Skull(s) - {skull_count} credit(s) deducted") return credits # 头奖:3个Bell if counts.get("Bell") == 3: credits += 5 print("Jackpot!!! +5 credits") # 常规奖励:2个相同元素 elif any(count == 2 for count in counts.values()): credits += 2 # 常规奖励加2分,可根据需求调整 print("Nice! You got a pair - +2 credits") # 未中奖 else: print("No win this time!") return credits fruit_machine()
关键优化点说明
- Counter统计:用
Counter(roll)一键获取所有元素的出现次数,无需逐个判断 - 参数同步:
fruit_roll返回修改后的credits,确保主逻辑的余额实时更新 - 前置校验:循环条件设为
credits >=2,避免用户在余额不足时继续抽奖 - 交互优化:打印每次抽中的结果,让用户清晰看到游戏过程
内容的提问来源于stack exchange,提问作者Caleb
相关产品推荐
相关产品推荐

