代码之家  ›  专栏  ›  技术社区  ›  Jake Carlile

在列表中找不到用户输入

  •  -1
  • Jake Carlile  · 技术社区  · 2 年前

    我试图获取用户输入,并在项目列表中找到它。 我可以成功地移动到一个位置,我可以问玩家他们想拿什么。 当代码到达 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.name]中询问: 我得到以下错误。查找如何检查列表中的字符串,结果显示这应该是可能的。

    enter image description here

    1 回复  |  直到 2 年前
        1
  •  0
  •   Alexey S. Larionov    2 年前

    对于代码行

    if ask in myPlayer.location.items[item.name]:
    

    错误在于不在 in ,错误就在这里 myPlayer.location.items[item.name]

    这是因为 myPlayer.location.items 是一个列表和 item.name 是一个字符串。您不能将字符串用作列表的索引。

    你的意思可能是:

        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 == item.name:
                myPlayer.inventory.append(item)
                print('You have picked up the ' + ask)
                print(myPlayer.inventory)
    

    注意这条线 if ask == item.name: ,它检查用户输入是否等于位置项目中的某个项目名称。那你就这么做 myPlayer.inventory.append(item) 将物品放入库存(而不是 ask ,它只是一个字符串)。