2013-07-10 2 views
0

Другой вопрос, связанный с моей мини-игрой. Я получил большую помощь по предыдущим вопросам, и я надеюсь, что я не трачу ваше время на такой, скорее всего, глупый вопрос. Вот код:Else not working IndexError: список index out of range

import time 
import random 
inventory = [] 
miningskill = 1 
fishingskill = 1 
gold = 0 
rawfish = ["Mackarel", "Cod", "Salmon", "Herring", "Tuna"] 
cookedfish = ["Cooked Mackarel", "Cooked Cod", "Cooked Salmon", "Cooked Herring", "Cooked Tuna"] 
trash = ["Old Shoe", "Thin Bone", "Rusted Empty Box", "Plank Fragment"] 
special = ["Copper Ring"] 
mackarel_range = range(1,3) 
cod_range = range(3,5) 
salmon_range = range(5,7) 
herring_range = range(7,9) 
tuna_range = range(9,11) 
oldshoe_range = range(11,16) 
plasticbag_range = range(16,21) 
rustedemptybox_range = range(21,26) 
plankfragment_range = range(26,31) 
copperring_range = range(31,32) 

print" _   _  _  _  ______ _  _  _ "    
print" | |   | |  (_)  ()  | ____(_) | | (_)"    
print" | |  ___ | |_ __ _ _ __ |/ ___ | |__ _ ___| |__ _ _ __ __ _ " 
print" | | /_ \| | '_ \| | '_ \/__| | __| |/__| '_ \| | '_ \/_` |" 
print" | |___| (_) | | |_) | | | | | \__ \ | | | \__ \ | | | | | | | (_| |" 
print" |______\___/|_| .__/|_|_| |_| |___/ |_| |_|___/_| |_|_|_| |_|\__, |" 
print"    | |             __/ |" 
print"    |_|            |___/ " 
time.sleep(2) 
print".  .           . .--." 
print" \ /    o       .'|  )" 
print" \ / .-. .--..--. . .-. .--.  o  | --:" 
print" \/ (.-' | `--. | ( )| |    |  )" 
print" '  `--'' `--'-' `- `-' ' `-  o  '---'o`--'" 
time.sleep(2) 
print "In this current version the first item in your inventory is sold." 

def sell_function(): 
    if inventory[0] in rawfish: 
     sold = inventory.pop(0) 
     global gold 
     gold = gold+5 
     print "You have sold a", sold, "for 5 gold coins!" 
    elif inventory[0] in trash: 
     sold = inventory.pop(0) 
     global gold 
     gold = gold+1 
     print "You have recycled a", sold, "for 1 gold coins!" 
    elif inventory[0] in special: 
     sold = inventory.pop(0) 
     global gold 
     gold = gold+10 
     print "You have sold a", sold, "for 10 gold coins!" 
    elif inventory[0] in cookedfish: 
     sold = inventory.pop(0) 
     global gold 
     gold = gold+8 
     print "You have sold a", sold, "for 8 gold goins!" 
    else: 
     print "Shopkeeper:'You can't sell that.'" 

def fish_function_beginner(): 
    random_fishingchance = random.randrange(1,32) 
    if 1 <= random_fishingchance < 3: 
     inventory.append("Mackarel") 
     print "You have reeled in a Mackarel!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 1 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 1" 
    elif 3 <= random_fishingchance < 5: 
     inventory.append("Cod") 
     print "You have reeled in a Cod!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 1 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 1" 
    elif 5 <= random_fishingchance < 7: 
     inventory.append("Salmon") 
     print "You have reeled in a Salmon!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 1 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 1" 
    elif 7 <= random_fishingchance < 9: 
     inventory.append("Herring") 
     print "You have reeled in a Herring!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 1 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 1" 
    elif 9 <= random_fishingchance < 11: 
     inventory.append("Tuna") 
     print "You have reeled in a Tuna!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 1 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 1" 
    elif 11 <= random_fishingchance < 16: 
     inventory.append("Old Shoe") 
     print "You have reeled in an Old Shoe..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 16 <= random_fishingchance < 21: 
     inventory.append("Thin Bone") 
     print "You have reeled in a Thin Bone..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 21 <= random_fishingchance < 26: 
     inventory.append("Rusted Empty Box") 
     print "You have reeled in a Rusted Empty Box..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 26 <= random_fishingchance < 31: 
     inventory.append("Plank Fragment") 
     print "You have reeled in a Plank Fragment..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 31 <= random_fishingchance < 32: 
     inventory.append("Copper Ring") 
     print "You have reeled in a ring shaped object covered in mud." 
     print "After cleaning it you notice it is a Copper Ring!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 2 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 2" 
    else: 
     print "It seems your fishing line has snapped!" 

def fish_function_amateur(): 
    random_fishingchance = random.randrange(1,29) 
    if 1 <= random_fishingchance < 3: 
     inventory.append("Mackarel") 
     print "You have reeled in a Mackarel!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 1 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 1" 
    elif 3 <= random_fishingchance < 5: 
     inventory.append("Cod") 
     print "You have reeled in a Cod!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 1 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 1" 
    elif 5 <= random_fishingchance < 7: 
     inventory.append("Salmon") 
     print "You have reeled in a Salmon!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 1 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 1" 
    elif 7 <= random_fishingchance < 9: 
     inventory.append("Herring") 
     print "You have reeled in a Herring!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 1 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 1" 
    elif 9 <= random_fishingchance < 11: 
     inventory.append("Tuna") 
     print "You have reeled in a Tuna!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 1 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 1" 
    elif 11 <= random_fishingchance < 15: 
     inventory.append("Old Shoe") 
     print "You have reeled in an Old Shoe..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 15 <= random_fishingchance < 19: 
     inventory.append("Thin Bone") 
     print "You have reeled in a Thin Bone..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 19 <= random_fishingchance < 24: 
     inventory.append("Rusted Empty Box") 
     print "You have reeled in a Rusted Empty Box..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 24 <= random_fishingchance < 29: 
     inventory.append("Plank Fragment") 
     print "You have reeled in a Plank Fragment..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 29 <= random_fishingchance < 30: 
     inventory.append("Copper Ring") 
     print "You have reeled in a ring shaped object covered in mud." 
     print "After cleaning it you notice it is a Copper Ring!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
     global fishingskill 
     fishingskill = fishingskill + 2 
     fishingskill_new = fishingskill 
     print "Your fishing skill is now",fishingskill_new,"It has increased by 2" 
    else: 
     print "It seems your fishing line has snapped!" 

def action_function(): 
    while True: 
     print "For a list of commands type 'help'" 
     action = raw_input("What do you want to do? >") 
     if action == "quit": 
      break 
      end 
     if action == "sell": 
      sell_function() 
     if action == "fish": 
      print "You throw your reel..." 
      time.sleep(10) 
      fish_skillcheck_function() 
     if action == "inventory": 
      print "You begin to open your inventory" 
      time.sleep(0.5) 
      print inventory 
     if action == "money": 
      print "You have",gold,"gold" 
     if action == "gold": 
      print "You have",gold,"gold" 
     if action == "cook": 
      fish_cookcheck_function() 
     if action == "fishingskill": 
      if 1 <= fishingskill < 75: 
       print "Your fishing skill is",fishingskill 
       print "Fishing Rank: Beginner" 
      elif 75 <= fishingskill < 150: 
       print "Your fishing skill is",fishingskill 
       print "Fishing Rank: Amateur" 
      elif 150 <= fishingskill < 300: 
       print "Your fishing skill is",fishingskill 
       print "Fishing Rank: Regular" 
      elif 300 <= fishingskill < 500: 
       print "Your fishing skill is",fishingskill 
       print "Fishing Rank: Seasoned" 
      elif 500 <= fishingskill < 750: 
       print "Your fishing skill is",fishingskill 
       print "Fishing Rank : Professional" 
      elif 750 <= fishingskill < 1000: 
       print "Your fishing skill is",fishingskill 
       print "Fishing Rank : Expert" 
      elif 1000 <= fishingskill < 9001: 
       print "Your fishing skill is",fishingskill 
       print "Fishing Rank : Fishing Grandmaster"  
      else: 
       print "Your skill is not available." 
     if action == "help": 
      print "Commands are= 'help' 'quit' 'sell' 'fish' 'fishingskill' 'gold' 'money' 'cook' and 'inventory" 
     if action == "cook": 
      fish_cookcheck_function() 

def fish_cookcheck_function(): 
    if inventory[0] == "Mackarel": 
     cooked = inventory.pop(0) 
     inventory.append("Cooked Mackarel") 
     print "You have cooked a", cooked 
    elif inventory[0] == "Cod": 
     cooked = inventory.pop(0) 
     inventory.append("Cooked Cod") 
     print "You have cooked a", cooked 
    elif inventory[0] == "Salmon": 
     cooked = inventory.pop(0) 
     inventory.append("Cooked Salmon") 
     print "You have cooked a", cooked 
    elif inventory[0] == "Herring": 
     cooked = inventory.pop(0) 
     inventory.append("Cooked Herring") 
     print "You have cooked a", cooked 
    elif inventory[0] == "Tuna": 
     cooked = inventory.pop(0) 
     inventory.append("Cooked Tuna") 
     print "You have cooked a", cooked 
    else: 
     "You can't cook this." 
     action_function() 

def fish_skillcheck_function(): 
    if 1 <= fishingskill < 75: 
     fish_function_beginner() 
    elif 75 <= fishingskill < 150: 
     fish_function_amateur() 
    else: 
     print "My fishing level is too low" 

action_function() 

Теперь, согласно тому, что я думаю, что должно произойти, если есть такая проблема, как там что-нибудь, чтобы продать в инвентаре не быть, то он должен пойти на еще часть

def sell_function(): 
     if inventory[0] in rawfish: 
      sold = inventory.pop(0) 
      global gold 
      gold = gold+5 
      print "You have sold a", sold, "for 5 gold coins!" 
     elif inventory[0] in trash: 
      sold = inventory.pop(0) 
      global gold 
      gold = gold+1 
      print "You have recycled a", sold, "for 1 gold coins!" 
     elif inventory[0] in special: 
      sold = inventory.pop(0) 
      global gold 
      gold = gold+10 
      print "You have sold a", sold, "for 10 gold coins!" 
     elif inventory[0] in cookedfish: 
      sold = inventory.pop(0) 
      global gold 
      gold = gold+8 
      print "You have sold a", sold, "for 8 gold goins!" 
     else: 
      print "Shopkeeper:'You can't sell that.'" 

Однако, как некоторые из вас, более продвинутые программисты, возможно, заметили, что есть некоторые проблемы. Это ошибка я получаю, когда я пытаюсь продать с пустой инвентаризацией (аналогично тому, что происходит, когда я пытаюсь готовить с пустым инвентарем):

Traceback (most recent call last): 
    File "C:\Users\Lolpin\Desktop\fishinglooptest.py", line 308, in <module> 
    action_function() 
    File "C:\Users\Lolpin\Desktop\fishinglooptest.py", line 231, in action_function 
    sell_function() 
    File "C:\Users\Lolpin\Desktop\fishinglooptest.py", line 40, in sell_function 
    if inventory[0] in rawfish: 
IndexError: list index out of range 

Когда я попытался найти ответил на вопросы о том же самом/подобная ошибка Я не могу поместить их в контекст моего кода. ._.

ответ

3

Используйте if inventory условия для проверки inventory пусто:

def sell_function(): 
    if inventory: 
     if inventory[0] in rawfish: 
     #other code 
    else: 
     print "Shopkeeper:'You can't sell that.'" 
+0

Еще раз спасибо: D – Lolpin

1

Проблема в том, что ваш список inventory пуст (поэтому нет 0-го элемента). Вы можете проверить это с помощью if заявления:

def sell_function(): 
    if not inventory: 
     print "your inventory is empty! You cannot sell anything" 
     return 
    if inventory[0] in rawfish: 
     ... 
+1

Неверный тест; 'if not inventory:' будет более полезным. :-) –

+0

+1. Не уверен, что я там думал ... Спасибо! – jh314

1

Также вы можете использовать Try/за исключением того, чтобы поймать, если ваш инвентарь имеет пункты

try: 
    if inventory[0] in rawfish: 
     #...all code 
except IndexError: 
    print "your inventory is empty" 
Смежные вопросы