我一直在开发类似Zork的基于文本的冒险游戏,并将其作为个人项目来尝试“速成班”自学python。我是编码的新手,所以我对基础知识不太了解。
在游戏中,我可以成功导航到创建的地图,并可以自由添加新房间/物品。我目前正在努力使“广告资源”系统正常运行。
目前,我的Room类中有一个名为“ roominv”的字典,它用作每个特定房间的清单。在玩家类别中,我还有一个名为“ 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次(错误),然后可以使用这些键四处走动或通过“取物”来拾取房间中的物品。
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)
也可以随意批评我的代码!我正在尝试学习,有经验的人的任何建议/意见都很好。
最佳答案
虽然不是代码审查,但我还会添加一些指针来修复您的其他错误,但首先要解决的问题是:
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上,请注意,代码审查仅应用于完整的有效代码,因此请确保没有任何修改。在此发布游戏之前,请先打破游戏中的错误。
运行示例:
>>> 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
{}
>>>
关于python - Python 3:如何在基于文本的游戏中从 list 中删除物品?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45571588/