Python 3.10自定义游戏:无法将武器名称转为对应整数数值求助
问题描述
开发的Python 3.10小型游戏中,希望玩家输入武器名称(如axe)时,将weapon变量转换为对应的伤害值整数(如25),而非保留字符串类型,目前无法实现该转换逻辑,寻求解决方法。
原始代码:
goblin = 20 dagger = 10 sword = 15 axe = 25 print('There is a goblin up ahead, what weapon would you like to choose? A dagger, a sword, or an axe?') weapon = input() print('You look around, and pick up the ' + weapon) if weapon > goblin: #A small game goblin = 20 dagger = 10 sword = 15 axe = 25 print('There is a goblin up ahead, what weapon would you like to choose? A dagger, a sword, or an axe?') weapon = input() print('You look around, and pick up the ' + weapon) if weapon > goblin: print('You swing the ' + weapon + ' at the goblin, cutting its head off in succession!') else: print('You swing the ' + weapon + ' at the goblin, but fail to do enough damage. You are defeated.') print('You swing the ' + weapon + ' at the goblin, cutting its head off in succession!') else: print('You swing the ' + weapon + ' at the goblin, but fail to do enough damage. You are defeated.')
解决方法
最简洁可靠的方式是用字典建立武器名称到伤害值的映射,既可以快速完成字符串到整数的转换,还能轻松处理非法输入的情况。
修改后的代码示例:
# 建立武器名称与伤害值的映射字典 weapon_damage_map = { 'dagger': 10, 'sword': 15, 'axe': 25 } goblin_health = 20 print('There is a goblin up ahead, what weapon would you like to choose? A dagger, a sword, or an axe?') # 转小写+去空格处理,兼容玩家输入大小写不同、带空格的情况 player_choice = input().strip().lower() # 验证输入是否合法 if player_choice not in weapon_damage_map: print('Invalid weapon! You hesitate and the goblin attacks. You are defeated.') else: weapon_name = player_choice weapon_dmg = weapon_damage_map[player_choice] print(f'You look around, and pick up the {weapon_name}') # 用武器伤害值与哥布林生命值比较 if weapon_dmg > goblin_health: print(f'You swing the {weapon_name} at the goblin, cutting its head off in succession!') else: print(f'You swing the {weapon_name} at the goblin, but fail to do enough damage. You are defeated.')
核心改动说明
- 使用字典替代分散的变量,直接关联武器名称和对应伤害值,逻辑更紧凑
- 用
strip().lower()处理输入,去除空格并统一为小写,避免因输入Axe或dagger(带空格)导致匹配失败 - 增加非法输入判断,处理玩家输入错误武器名的场景
- 拆分出
weapon_name(用于文本输出)和weapon_dmg(用于数值比较)两个变量,同时满足展示和逻辑判断需求 - 移除原代码中重复的变量定义和冗余逻辑,简化整体结构
内容的提问来源于stack exchange,提问作者Kosstheboss123
相关产品推荐
相关产品推荐

