You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python文字游戏如何实现输入首字母匹配对应完整操作指令

文字游戏首字母输入识别实现(中文适配版)

核心改动说明

  • 新增首字母匹配逻辑:支持输入s/d/q直接对应偷取(原Steal)、合作(原Deal)、退出(原Quit)三个操作,自动兼容大小写、输入首尾空格的异常场景
  • 补全原代码缺失的random模块导入、Quit退出逻辑,修正原代码逻辑冗余、英文拼写错误问题
  • 所有交互提示、结果判定内容已全部翻译为中文

完整可运行代码

import random

# 输入字符与操作的映射字典
operate_map = {
    "s": "偷取",
    "d": "合作",
    "q": "退出"
}

while True:
    # 获取并标准化用户输入
    input_content = input("请选择操作:偷取/合作/退出 [对应输入s/d/q]?: ").strip().lower()
    # 非法输入校验
    if input_content not in operate_map:
        print("输入无效,请输入s/d/q中对应字符\n")
        continue
    
    human_choice = operate_map[input_content]
    # 退出操作处理
    if human_choice == "退出":
        print("游戏已退出")
        break
    
    print(f"\n你选择了:{human_choice}")
    # 电脑随机选择操作
    comp_options = ["偷取", "合作"]
    comp_choice = random.choice(comp_options)
    print(f"电脑选择了:{comp_choice}\n")
    
    # 胜负判定
    if human_choice == comp_choice:
        if human_choice == "偷取":
            print("双方都选择偷取!太贪婪,你们都没有获得任何奖励")
        else:
            print("平局!双方各获得50奖励")
    elif human_choice == "偷取" and comp_choice == "合作":
        print("你赢了!获得100奖励")
    else:
        print("你输了!电脑获得100奖励")
    print("-" * 30 + "\n")

内容的提问来源于stack exchange,提问作者McFez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:45:07