2016-09-29 103 views
1

我知道這是一個簡單的修復 - 但我不能爲我的生活弄清楚如何解決這個IndexError。Python索引超出範圍時,缺少用戶用戶輸入

def show_status(): 
    print("\nThis is the " + rooms[current_room]["name"]) 



rooms = { 

     1 : { "name" : "Highway" , 
       "west" : 2 , 
       "east" : 2 , 
       "north": 2 , 
       "south": 2} , 
     2 : { "name" : "Forest" , 
       "west" : 1 , 
       "east" : 1 , 
       "north": 1 , 
       "south": 1} , 
     } 

current_room = 1 

while True: 

    show_status() 

    move = input(">> ").lower().split() 


    if move[0] == "go": 
     if move[1] in rooms[current_room]: 
      current_room = rooms[current_room][move[1]] 
     else: 
      print("you can't go that way!") 
    else: 
     print("You didn't type anything!") 

如果用戶按下「返回」沒有把一個價值在移動,遊戲以「列表索引超出範圍」崩潰。我不明白爲什麼「其他」在while循環中沒有捕捉到。

+1

的崩潰發生:你需要檢查'如果移動和移動[0] == 「走出去」',例如。問題是當元素爲零時試圖訪問'move [0]'。 –

回答

1

move[0]檢查列表的第一個成員,並且如果move是空的,則拋出IndexError,因爲當用戶簡單地按下回車鍵時。您可以先檢查move是否爲真:如果不是,則and運營商將規避下一次檢查。

看來您期待用戶輸入一個空格,導致兩個成員。您應該檢查len(move) == 2以確保這一點。

修改如下:`else`前

# ... 
move = input(">> ").lower().split() 

if len(move) == 2 and move[0] == "go": 
    # the rest 
+0

你們太棒了。謝謝!回到製作真棒文本冒險。 – Windtalker87