2012-03-29 80 views
1

我有一個問題,試圖製作一個小型文本幻想類型的遊戲,涉及每種類型的實體(牆,玩家,書籍等)的類。我有一類叫做房間,看起來像這樣:Python對象在列表中尚未?

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()

每個對象,(蠟燭,匕首,長袍等)具有類,以及:

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 
+4

aaaahhh牆上找到該項目的指標! – Puppy 2012-03-29 04:12:04

+3

那麼,至少我們不能抱怨他*沒有*顯示他到目前爲止所嘗試的內容。 – 2012-03-29 04:14:12

+1

你知道'蠟燭'和'蠟燭'是不同的物體,對吧? – 2012-03-29 04:15:03

回答

5

目的candle在列表中,但字符串'candle'不是。您可能希望與對象的字典來解決這個問題:

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

然後,您可以通過代碼

popp = room.items.index(objects[input2]) 
+0

哇!這工作完美!只是要記住添加對象到列表;)再次非常感謝!成功的甜蜜信息:'天花板上有一個洞,你似乎已經墜落了,有 沒有辦法備份......你在這裏看到:蠟燭 現在是什麼?拿 拿什麼?蠟燭 你把蠟燭放在你的揹包裏。 天花板上有一個洞,你似乎已經倒下了,有 沒有辦法備份......你看到這裏:現在是什麼? – CR0SS0V3R 2012-03-29 04:56:37