Python游戏开发:无法在物品列表中匹配用户输入的问题
问题描述
我正在开发一款文字冒险游戏,已成功实现场景移动功能,当前需完成拾取物品功能。当代码执行到if ask in myPlayer.location.items[item.name]:时出现错误,我查阅了字符串在列表中存在性的判断方法,但问题仍未解决。完整代码如下:
#MARK: Imports import sys #MARK: Classes class Player(object): def __init__(self, name, location, job): self.name = name self.location = location self.job = job self.inventory = [] self.gameOver = False class Room(object): def __init__(self, name, description): self.name = name self.description = description self.exits = {} self.items = [] class Item(object): def __init__(self, name, description): self.name = name self.description = description class Job(object): def __init__(self, name, health): self.name = name self.health = health #MARK: Locations yourHouse = Room("Your House", "This is your small house. Nothing has changed here") townHall = Room("Town Hall", "This is the Town Hall. Sometimes people gather here to make decissions for the town") townPark = Room("Town Park", "This is the towns small Park.\nThere is a small pond with a park bench on it's edge where you can sit and feed the ducks.\nA few trees provide shade.") townGeneralStore = Room("The General Store", "The General Store is the largest building in town. Here you can buy almost everything you need.") #MARK: Exits yourHouse.exits = {'north': townHall, 'west': townPark} townHall.exits = {'south': yourHouse, 'west': townGeneralStore} townPark.exits = {'east': yourHouse, 'north': townGeneralStore} townGeneralStore.exits = {'south': townPark, 'east': townHall} #MARK: Jobs fighter = Job("Fighter", 40) sneak = Job("Sneak", 20) #MARK: Create player myPlayer = Player("", yourHouse, "") #MARK: Create items shovel = Item('Shovel', "You find a sturdy shovel. It looks like it could do some good bashing.") stick = Item('Stick', 'You find a fragile looking stick, it looks like it could break easily.') #MARK: Place Items townHall.items.append(shovel) townPark.items.append(stick) print('\n' + myPlayer.location.name) print(myPlayer.location.description) room_exits = "\n" + "The exits are: \n" for character in room_exits: sys.stdout.write(character) sys.stdout.flush() for exit in myPlayer.location.exits: print(exit) #MARK: Main game loop while myPlayer.gameOver is False: # Start player in their house action = input('>') plaAction = action.lower() # Movement if plaAction in ['north', 'south', 'east', 'west']: if plaAction in myPlayer.location.exits: myPlayer.location = myPlayer.location.exits[action] print("\n" "You went to " + myPlayer.location.name + '.') print("\n" + myPlayer.location.description) for exit in myPlayer.location.exits: print(exit) # Pick up items if plaAction in ['get']: ask = input("What would you like to pick up?\n") print(type(ask)) print(type(myPlayer.location.items)) for item in myPlayer.location.items: if ask in myPlayer.location.items[item.name]: myPlayer.inventory.append(ask) print('You have picked up the ' + ask) print(myPlayer.inventory) # Exit Game command if plaAction == 'exit': myPlayer.gameOver = True
错误原因分析
- 索引使用错误:
myPlayer.location.items是存储Item对象的列表,而非字典,不能用item.name作为索引访问列表元素,这是触发报错的直接原因。 - 逻辑判断错误:判断用户输入物品是否存在的逻辑有误——应该对比用户输入的名称与物品对象的
name属性,而非用in去判断一个不存在的列表元素。 - 功能遗漏:拾取物品后未从房间物品列表中移除该物品,会导致玩家可重复拾取同一物品。
修正后的代码
核心拾取功能修正
替换原代码中「Pick up items」部分的代码:
# Pick up items if plaAction in ['get']: ask = input("What would you like to pick up?\n").lower() picked_success = False # 遍历房间内的物品对象 for item in myPlayer.location.items: # 统一转小写,避免大小写不匹配问题 if ask == item.name.lower(): # 将物品对象加入背包,而非字符串 myPlayer.inventory.append(item) # 从房间移除该物品 myPlayer.location.items.remove(item) print(f'You have picked up the {item.name}') print(item.description) # 打印当前背包状态 print("\nYour inventory:") for inv_item in myPlayer.inventory: print(f"- {inv_item.name}") picked_success = True break if not picked_success: print(f"There's no {ask} in this room!")
移动功能小修正
原移动代码中使用原始输入action作为字典键,可能因大小写不匹配报错,改为使用转小写后的plaAction:
# Movement if plaAction in ['north', 'south', 'east', 'west']: if plaAction in myPlayer.location.exits: myPlayer.location = myPlayer.location.exits[plaAction] print(f"\nYou went to {myPlayer.location.name}.") print(f"\n{myPlayer.location.description}") # 打印当前房间出口 print("\nExits:") for exit_dir in myPlayer.location.exits: print(f"- {exit_dir}")
额外优化建议
- 初始化玩家时可以添加姓名输入、职业选择逻辑,让游戏更完整;
- 可以给
Player类添加查看背包的方法,方便后续扩展; - 物品描述可以在查看背包时显示,提升游戏体验。
内容的提问来源于stack exchange,提问作者Jake Carlile
相关产品推荐
相关产品推荐

