Python游戏嵌套循环问题:player_choice无效时如何不重选user_choice
根因分析
你代码里player_choice输入无效后执行的continue作用于最外层的游戏主循环,触发后会直接回到主循环开头重新请求user_choice输入,不符合仅重输player_choice的需求。同时原代码还存在user_choice输入无效后,仍会触发后续player_choice输入请求的小问题。
修复方案
给player_choice的输入逻辑增加独立的子循环,仅当输入有效值时才退出子循环执行后续逻辑,无效输入直接在子循环内重复请求,不跳出到外层主循环;同时给user_choice无效的分支补充continue,避免无意义的后续判断。
修复后的完整代码如下:
def playGame(wordList): hand = [] while True: # 询问用户游戏操作选择 user_choice = input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ') # 输入e直接结束游戏 if user_choice == 'e': break elif user_choice == 'r' and len(hand) == 0: print('You have not played a hand yet. Please play a new hand first!') # 输入无效命令提示后回到主循环重输 elif user_choice not in ('n', 'r'): print('Invalid command.') continue # 输入n或r时询问游玩方 if user_choice in ('n', 'r'): # 新增子循环单独处理player_choice输入校验 while True: player_choice = input('Enter u to have yourself play, c to have the computer play: ') # 人类玩家游玩逻辑 if player_choice == 'u': if user_choice == 'n': hand = dealHand(HAND_SIZE) playHand(hand, wordList, HAND_SIZE) elif user_choice == 'r' and len(hand) != 0: playHand(hand, wordList, HAND_SIZE) else : print('You have not played a hand yet. Please play a new hand first!') break # 电脑玩家游玩逻辑 elif player_choice == 'c': if user_choice == 'n': hand = dealHand(HAND_SIZE) compPlayHand(hand, wordList, HAND_SIZE) elif user_choice == 'r' and len(hand) != 0: compPlayHand(hand, wordList, HAND_SIZE) else: print('You have not played a hand yet. Please play a new hand first!') break # 输入无效时仅在子循环内重输,不触发外层主循环 else: print('Invalid command.')
内容的提问来源于stack exchange,提问作者Beets Noms
相关产品推荐
相关产品推荐

