Python 3:如何从基于文本的游戏中删除库存中的项目?

时间:2017-08-08 14:51:25

标签: python class dictionary inventory

我一直在研究类似Zork的基于文本的冒险游戏,作为个人项目,以及#34; Crash course"自学蟒蛇。我一般都是编码新手,所以我对基础知识模糊不清。

我已经达到了我在游戏中的位置,我可以成功导航我创建的地图,并可以自由添加新的房间/项目。我目前正致力于制作"库存"系统正常工作。

目前,我有一本名为" roominv"在我的Room类中,作为每个特定房间的库存。我还有一本名为" bag"在作为玩家库存的玩家类中。

目前游戏有缺陷且未完成,所以要拿起一件物品,你必须拿起当前房间里的所有物品,但这不是我遇到的麻烦。

一旦玩家拿起那个房间的物品,我就无法弄清楚如何清空roominv字典。现在我可以将这些项目添加到播放器包中,但它会创建一个副本,而无需将它们从roominv中删除。

我尝试过使用del,delattr和pop,但要么我没有正确使用它们(这是我假设的),或者说这不是正确的方法。我也试过.remove,我在下面的代码中留下了。它返回此错误消息

Traceback (most recent call last):
  File "C:/Users/Daniel/Desktop/PythonPR/Flubbo'sLatestBuild.py", line 104, in <module>
    player = Player("Jeff", 100, [], 'introd', command)
  File "C:/Users/Daniel/Desktop/PythonPR/Flubbo'sLatestBuild.py", line 97, in __init__
    addToInventory(self.room.roominv)
  File "C:/Users/Daniel/Desktop/PythonPR/Flubbo'sLatestBuild.py", line 82, in addToInventory
    Room.roominv.remove(item)
AttributeError: type object 'Room' has no attribute 'roominv'

这与使用del或delattr时出现的错误相同。 任何提示,建议或伪代码将非常感激,如果我只是完全错误的方式,请告诉我哈哈。

要开始游戏,您必须键入n,w,e或s 3次(Bug),然后您可以使用这些键走动或者使用&#34; Take Items&取出物品#34 ;.

world = {}
command = input('>>> ')


class Items:
    def __init__(self, name, info, weight, position):
        self.name = name
        self.position = position
        self.info = info
        self.weight = weight


class Weapon(Items):
    def __init__(self, name, info, damage, speed, weight, position):
        super().__init__(name, info, weight, position)
        self.damage = damage
        self.speed = speed


sword = Weapon("Sword", "A sharp looking sword. Good for fighting goblins!", 7, 5, 5, 0)
knife = Weapon("Knife", "A wicked looking knife, seems sharp!", 5, 7, 3, 5)
stick = Weapon("Stick", "You could probably hit someone with this stick if you needed to", 2, 3, 3, 2)
shackkey = Items("Shack Key", "A key! I wonder what it opens.", .01, 3)
cottagekey = Items("Cottage Key", "An ornate key with an engraving of a small cottage on one side", .01, 5)
Moonstone = Items("Moonstone", "A smooth white stone that seems to radiate soft white light", .05, 6)
flower = Items("Flower", "A beautiful wildflower", .001, 1)


class Room:

    def __init__(self, name, description, exits, actions, roominv):  # Runs every time a new room is created
        self.name = name
        self.description = description
        self.exits = exits
        self.actions = actions
        self.roominv = roominv


world['introd'] = Room('introd', "You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.", {'n' or 'north' or 'go north': "clearing"}, {"Search the ground", "Go North"}, {'sword': sword})


world['clearing'] = Room('clearing', "You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. \
To the South is the way you entered the forest. A well worn path goes to the East. In the distance a harp can be heard.", {'s' or 'south' or 'go south': "introd", 'e' or 'east' or 'go east': "forest path"}, {"Take flower", "Go south", "Go East"}, {'flower': flower})



class Player:

    def __init__(self, name, health, bag, room_name, move):
        self.name = name
        self.health = health
        self.bag = bag
        self.room = world[room_name]
        self.move = move

        def travel(self, direction):
            if direction not in self.room.exits.keys():
                print("You can't go that way!")
            else:
                new_room_name = self.room.exits[direction]
                print("moving to", new_room_name)
                self.room = world[new_room_name]
                print(self.room.description)
                print(self.room.actions)

        def addToInventory(item):
            self.bag.append(item)
            Room.roominv.remove(item)

        command = input('>>> ')
        while command != "":
            command = input('>>> ')
            if command in {'n', 'e', 's', 'w', 'north', 'south', 'east', 'west', 'go north', 'go south', 'go east', 'go west'}:
                travel(self, command)
            elif command == 'look':
                print(self.room.description)
                print('Exits', self.room.exits.keys())
            elif command == '':
                print('You have to say what it is you want to do! Unfortunately due to a bug you must now restart the game. We are working on fixing this as soon as possible. Sorry!')
            elif command == 'search':
                print(self.room.roominv)
            elif command == 'Take Items':
                addToInventory(self.room.roominv)
            elif command == 'Inventory':
                print(self.bag)
            else:
                print('Invalid command')


player = Player("Jeff", 100, [], 'introd', command)

也可以随意批评我的代码!我试图学习,更有经验的人的建议/评论会很棒。

3 个答案:

答案 0 :(得分:2)

虽然不是代码审查,但我还会添加一些指针来修复您的其他错误,但首先是手头的问题:

Room.roominv.remove(item)

Room是一个类,而不是一个对象,所以你不能要求它roominv 相反,您需要self.room.roominv,但由于.remove不是dict的成员,因此不起作用,我建议进行以下更改:

您的'Take Items'命令应为:

elif command.split()[0] == 'Take':
    for key in list(self.room.roominv.keys()):
        if self.room.roominv[key].name == command.split()[1]:
            addToInventory(key)

这将允许用户仅使用可用的特定项目,并允许用户指定他们想要选择的项目。

然后您的addToInventory功能可以是:

def addToInventory(self,key):
    self.bag.append(self.room.roominv[key])
    del self.room.roominv[key]

如果房间中有多个项目,这将处理仅删除给定项目。

del关键字从字典中删除给定的键/项对。

关于你的其他问题,你的错误在这里:

elif command == '':
    print('You have to say what it is you want to do! Unfortunately due to a bug you must now restart the game. We are working on fixing this as soon as possible. Sorry!')
只需更改command的内容即可修复

elif command == '':
    print('You have to say what it is you want to do!')
    command = '#'

为了确保您需要多次输入指令,我建议您执行以下操作:

从代码顶部删除command = input('>>> ')

command = input('>>> ')

替换while command != ""循环上方的command = ' '

并更新您的Player以取消move(这意味着编辑__init__函数以及代码底部的player的初始创建:player = Player("Jeff", 100, [], 'introd')

最后,挑剔,为什么不把你的while循环放在一个函数中?所有这些导致:

class Player:
    def __init__(self, name, health, bag, room_name):
        self.name = name
        self.health = health
        self.bag = bag
        self.room = world[room_name]

    def travel(self, direction):
        if direction not in self.room.exits.keys():
            print("You can't go that way!")
        else:
            new_room_name = self.room.exits[direction]
            print("moving to", new_room_name)
            self.room = world[new_room_name]
            print(self.room.description)
            print(self.room.actions)

    def addToInventory(self, key):
        self.bag.append(self.room.roominv[key])
        del self.room.roominv[key]

    def play(self):
        command = " "
        while command != "":
            command = input('>>> ')
            if command in {'n', 'e', 's', 'w', 'north', 'south', 'east', 'west', 'go north', 'go south', 'go east', 'go west'}:
                self.travel(command)
            elif command == 'look':
                print(self.room.description)
                print('Exits', self.room.exits.keys())
            elif command == '':
                print('You have to say what it is you want to do!')
                command = '#'
            elif command == 'search':
                print(self.room.roominv)
            elif command.split()[0] == 'Take':
                itemTaken = False
                for key in list(self.room.roominv.keys()):
                    if self.room.roominv[key].name == command.split()[1]:
                        self.addToInventory(key)
                        itemTaken = True
                if not itemTaken:
                    print("I can't find that")
            elif command == 'Inventory':
                print(self.bag)
            else:
                print('Invalid command')

player = Player("Jeff", 100, [], 'introd')
player.play()

这些更改会导致需要进行一些其他更改,例如查看广告资源时,打印出每个项目的.name,而不是对象本身。

完整的代码审核还可以进行更多更改,但是您应该在Code Review上发布代码,请注意代码审核只应用于完整的代码< / em>,所以请确保在发布之前没有任何游戏破坏错误。

示例运行:

>>> n
moving to clearing
You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. To the South is the way you entered the forest. A well worn path goes to the East. In the distance a harp can be heard.
{'Go East', 'Take flower', 'Go south'}
>>> s
moving to introd
You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.
{'Search the ground', 'Go North'}
>>> n
moving to clearing
You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. To the South is the way you entered the forest. A well worn path goes to the East. In the distance a harp can be heard.
{'Go East', 'Take flower', 'Go south'}
>>> s
moving to introd
You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.
{'Search the ground', 'Go North'}
>>> search
{'sword': <__main__.Weapon object at 0x00000000040B9470>}
>>> Take sword
I can't find that
>>> Take Sword
>>> Inventory
[<__main__.Weapon object at 0x00000000040B9470>]
>>> search
{}
>>> 

答案 1 :(得分:0)

您的addInventory方法错误。首先,您必须使用实例变量self.room而不是类Room本身。其次,如果你想要的是清理整个roominv词典,你应该尝试:

def addToInventory(item):
    self.bag.append(item)
    self.room.roominv.clear()  # this will clear the roominv dictionary

更新

如果你想从roominv中删除一个元素,你可以这样做:

self.room.roominv.pop(key, None)

如果密钥不存在于dict中,None将阻止pop引发KeyError

答案 2 :(得分:0)

little_birdie说你试图访问类room的属性,而不是获取Room的实例。

此外,您的roominvdict。只有list获得了方法remove()。 要从字典中删除密钥,请使用:

del dict_name[key]

我刚看到,你不是只想挑选单品,而是一次性。 因此,您可以使用:

self.room.roominv.clear()

Here is a little example可能会帮助您完成工作。

你可能想要做的是这样的事情:

def addToInventory(item):
    self.bag.append(item)
    del self.room.roominv.clear()