Python石头剪刀布游戏添加错误输入捕获条件判断实现方案
Python石头剪刀布游戏无效输入捕获实现
你现有代码的输入校验逻辑仅做了静默重试,没有给用户明确的错误反馈,我们只需在get_player_choice函数中补充分层条件判断,就能实现不同错误场景的对应提示,同时顺手修复原代码中is_draw函数未显式返回布尔值的潜在bug。
核心修改点
- 对用户输入做分层校验:依次判断空输入、输入长度、合法字符匹配三类错误场景
- 每个错误场景输出针对性提示,明确告知用户错误原因和正确输入规则
- 保留原有循环重试逻辑,输入错误后不会中断游戏,直接回到输入步骤
- 统一做小写转换处理,兼容用户输入大写R/P/S的场景
修改后完整可运行代码
import random CHOICES = 'rps' # 选项映射,用于提示信息展示 CHOICE_MAP = { 'r': '石头(Rock)', 'p': '布(Paper)', 's': '剪刀(Scissors)' } def get_player_choice(): """获取用户输入并校验合法性,非法输入抛出对应提示后重试""" player_choice = None while player_choice is None: raw_input = input('Choices: \n(R)ock \n(P)aper \n(S)cissors \n\nPick: ').strip() # 空输入判断 if not raw_input: print("*错误:输入不能为空,请输入r/R/p/P/s/S选择对应选项*\n") continue # 输入长度判断 if len(raw_input) > 1: print("*错误:请输入单个字符r/p/s,无需输入完整单词或多个字符*\n") continue player_choice = raw_input.lower() # 合法选项判断 if player_choice not in CHOICES: print(f"*错误:无效选项「{raw_input}」,仅支持输入r(石头)、p(布)、s(剪刀)*\n") player_choice = None return player_choice def get_computer_choice(): """电脑随机选择合法选项""" computer_choice = random.randint(0, 2) computer_choice = CHOICES[computer_choice] return computer_choice def is_draw(player_choice, computer_choice): """判断是否平局""" return player_choice == computer_choice def print_winner(player_choice, computer_choice): """判断胜负并输出结果""" win_rule = { 'r': 's', 's': 'p', 'p': 'r' } if win_rule[player_choice] == computer_choice: print('你赢了!') print(f'{CHOICE_MAP[player_choice]} 击败 {CHOICE_MAP[computer_choice]}') else: print('电脑赢了!') print(f'{CHOICE_MAP[computer_choice]} 击败 {CHOICE_MAP[player_choice]}') def play_game(): """游戏主流程""" player_choice = get_player_choice() computer_choice = get_computer_choice() if is_draw(player_choice, computer_choice): print(f"平局!双方都选择了{CHOICE_MAP[player_choice]}") else: print(f"电脑选择了:{CHOICE_MAP[computer_choice]}") print(f"你选择了:{CHOICE_MAP[player_choice]}") print_winner(player_choice, computer_choice) if __name__ == "__main__": play_game()
错误提示触发场景
- 直接回车不输入内容:触发空输入错误提示
- 输入超过1个字符(比如输入
rock、sp、12):触发长度错误提示 - 输入r/p/s以外的单字符(比如
a、1、?、z):触发无效选项提示,明确展示用户输入的错误内容 - 输入大写
R/P/S可正常识别,不会判定为错误
内容的提问来源于stack exchange,提问作者Eddy Yahwin
相关产品推荐
相关产品推荐

