Python遍历玩家列表实现奇偶游戏循环功能故障排查
问题分析与修复方案
核心问题点
- 外层循环逻辑错误:玩家交互、骰子投掷的代码放在了
while index < len(players)循环外,导致只有第一个玩家能触发逻辑,后续玩家无法执行新的输入和投掷 - 内层循环条件错误:
choice != "o" or choice != "e"永远为真(任何输入不可能同时是o和e),应该改为choice != "o" and choice != "e" - 索引递增时机错误:
index +=1放在内层循环中,输入错误时会直接跳过玩家,应该放在每个玩家处理完成后 - 骰子值未重置:所有玩家共用同一个骰子结果,应该每个玩家重新投掷
修复后的代码
class OddOrEven(Game): def oddoreven(self): # 添加self参数,作为实例方法 index = 0 while index < len(players): current_player = players[index] print(f"Hey {current_player}, Odd (o) or Even (e)?") # 获取用户输入并处理格式 choice = input('> \u001b[1m').strip().lower() print('\u001b[0m', end='') # 验证输入合法性 while choice != "o" and choice != "e": print("Invalid choice.") choice = input('> \u001b[1m').strip().lower() print('\u001b[0m', end='') # 每个玩家重新投掷骰子 randomdice = d.roll() # 判断胜负 if choice == "o": if randomdice in (1,3,5): print(f"Congratulations, {current_player}! You win!") else: print(f"Sorry, {current_player}! You lose!") else: # choice == "e" if randomdice in (2,4,6): print(f"Congratulations, {current_player}! You win!") else: print(f"Sorry, {current_player}! You lose!") print() # 处理完当前玩家后,索引递增 index += 1
额外优化建议
用for current_player in players替代索引循环,代码更简洁易读:
class OddOrEven(Game): def oddoreven(self): for current_player in players: print(f"Hey {current_player}, Odd (o) or Even (e)?") choice = input('> \u001b[1m').strip().lower() print('\u001b[0m', end='') while choice != "o" and choice != "e": print("Invalid choice.") choice = input('> \u001b[1m').strip().lower() print('\u001b[0m', end='') randomdice = d.roll() if choice == "o": result = "win" if randomdice % 2 != 0 else "lose" else: result = "win" if randomdice % 2 == 0 else "lose" print(f"{'Congratulations' if result == 'win' else 'Sorry'}, {current_player}! You {result}!") print()
内容的提问来源于stack exchange,提问作者Epilox
相关产品推荐
相关产品推荐

