gpt4 book ai didi

Python 对象是否在列表中?

转载 作者:太空宇宙 更新时间:2023-11-04 09:15:30 24 4
gpt4 key购买 nike

我在尝试制作一个涉及每种类型实体(墙、玩家、书等)类的小型文本幻想类型游戏时遇到了问题。我有一个名为 room 的类,如下所示:

class Room:

def __init__(self, desc, items, wallF, wallB, wallL, wallR, isdark):
self.desc = desc
self.items = items
self.wallF = wallF
self.wallB = wallB
self.wallL = wallL
self.wallR = wallR
self.isdark = False

现在我有两个这样定义的房间(不是说它是对的):

roomstart = Room('There is a hole in the ceiling where you seemed to have fallen through, there is no way back up...', [candle], True, False, False, False, False)
room2 = Room('You enter a small cobblestone cavort. It is dark, and the smell of rot pervades you', [spellbook], False, True, False, True, True)

现在,问题是这样的:当我运行程序时,它工作正常,直到我尝试从 roomstart 中取出蜡烛,然后它吐出蜡烛不在列表中的错误:

(<type 'exceptions.ValueError'>, ValueError("'candle' is not in list",), <traceb
ack object at 0x00B8D648>)

(是的,我确实使用了 sys.exc_info())

每个对象(蜡烛、 Dagger 、长袍等)也有一个类:

class Object:

def __init__(self, desc, worth, emitslight, readable, wearable, name):
self.desc = desc
self.worth = worth
self.emitslight = emitslight
self.readable = readable
self.wearable = wearable
self.name = name

这是用户输入的代码:

def handleinput():
global moves
room = Player.location
if room.isdark == True:
print 'It is rather dark in here...'
else:
print room.desc, 'You see here:',
for i in room.items:
print i.name
input = str(raw_input('What now? ')).lower()
if 'look' in input:
if room.isdark==True:
print "You can't see anything! Its too dark."
else:
print 'You see:',room.desc, room.items.name
if room.wallF == True:
print 'There is an exit to the front.'
elif room.wallB == True:
print 'There is an exit behind you.'
elif room.wallL == True:
print 'There is an exit to your left.'
elif room.wallR == True:
print 'There is an exit to your right.'

elif 'grab' in input:
if room.isdark==True:
print 'You flail about blindly in the dark room!'
else:
input2 = str(raw_input('Take what? '))
try:
popp = room.items.index(input2)
print popp
except:
print sys.exc_info()
print input2.title(),"doesn't exist!"
else:
print "You take the",input2,"and store it in your knapsack."
room.items.pop(popp)
Player.inventory.append(input2)

elif 'wipe face' in input:
os.system('cls')
moves += 1

最佳答案

对象 candle 在列表中,但字符串 'candle' 不在。您可能希望使用对象字典来解决此问题:

objects = {}
objects['candle'] = candle
objects['robe'] = robe
...

然后,您可以通过

找到项目的索引
popp = room.items.index(objects[input2])

关于Python 对象是否在列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9918950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com