Python老虎机代码问题:三符号匹配时奖金计算不符合预期
老虎机Jackpot功能问题修复
问题根源
- 条件顺序错误:三个符号相同的判断(包括Jackpot)被放在两个符号相同的判断之后。当三个符号相同时,必然满足“两个符号相同”的条件,导致高奖金规则永远不会被触发。
- Jackpot判断逻辑错误:原代码中
all(slot1 and slot2 and slot3) == e的写法完全错误,无法正确识别三个符号都是Jackpot的情况——这个表达式实际是判断三个非空字符串的逻辑与结果(永远为True)是否等于'jackpot',结果永远为False。
修正后的代码
if __name__ == '__main__': import random a = 'orange' b = 'strawberry' c = 'pineapple' d = 'apple' e = 'jackpot' slots = [a, b, c, d, e] winnings = 0 print('Play slot machine? (yes or no)') play = input() while play == 'yes': print('Please enter a bet amount:') bet = float(input()) slot1 = random.choice(slots) slot2 = random.choice(slots) slot3 = random.choice(slots) print(slot1, " ", slot2, " ", slot3) # 最高优先级:三个都是Jackpot if slot1 == slot2 == slot3 == e: winnings = bet * 10 # 次优先级:三个普通符号相同 elif slot1 == slot2 == slot3: winnings = bet * 4 # 最低优先级:任意两个符号相同 elif slot1 == slot2 or slot2 == slot3 or slot1 == slot3: winnings = bet * 2 else: winnings = 0 print(winnings) print('Play slot machine again? (yes or no):') play = input()
关键修改说明
- 调整条件优先级:将高奖金规则放在最前面,确保三个符号相同的情况不会被低优先级的规则拦截。
- 修正Jackpot判断:使用
slot1 == slot2 == slot3 == e直接判断三个符号均为Jackpot,逻辑清晰且正确。 - 简化两符号相同判断:用
or合并三个两符号相同的条件,代码更简洁,逻辑不变。
内容的提问来源于stack exchange,提问作者Jacob Kramer
相关产品推荐
相关产品推荐

