2014-01-07 2 views
0

Я работаю над кодом для своей игры, и у меня возникла проблема. Я заранее извиняюсь, если это трудно понять. Первый раздел работает отлично. Существует большой объем кода, поэтому я добавил его в codepad.org для более простого обмена. Вот ссылка; http://codepad.org/kT8szBb2Большое количество if, elif, else, вызывающих проблемы

Линии 108 и 142 должны работать вместе. Я пробовал разные вещи, как добавление в этом:

if True: 

, чтобы попытаться изменить уровень отступа, но по каким-либо причинам это не похоже на работу. Любые предложения работают; Я готов попробовать что угодно, даже если это означает переписывание всего сегмента. Заранее спасибо.

+5

Святой Иисус ..... Вы просите о проблемах с этим кодом. Я бы предложил вам реорганизовать его. – jramirez

+0

узнать о «рефакторинге» и функциях – praveen

+1

Рекомендация: научитесь использовать функции и циклы. –

ответ

5

Хорошо, я думаю, что нашел проблему. Вы не совсем понимаете, как работает отступ. У вас есть код, который выглядит так:

if a: 
    if b: 
     if c: 
A() 
else: 
    B() 
    else: 
     C() 

Это не то, как работает Python. Python работает со следующей структурой:

if a: 
    A() 
elif b: 
    B() 
elif c: 
    C() 

Я действительно хотел бы знать, где эта ошибка в понимании пришли, потому что это какой-то очень грязный код.

+0

Ничего себе, понимая, что ошибка одна, но объяснить это так ясно - это качество! Если вы не учитель, то, возможно, вы должны стать одним;) – BartoszKP

0

На самом деле нет необходимости в всех этих if. Вы должны абсолютно использовать цикл for.

weapons = { 1:'sword', 2:'mace', 3:'bow'} 

for wep in weapons: 
    print('the {} is available'.format(weapons[wep])) 

выходы:

the sword is available 
the mace is available 
the bow is available 
2

Я взял на себя смелость рефакторинга кода, чтобы быть здоровым.

def weaponsel(): 
    swep = None 
    #again, I'm not really sure where this is coming from or what you're doing with it 
    #so it's hard to say if you should be saving the contents of swep before you run 
    #the function, possibly to return if you select /return/ at the first prompt? 
    while swep is None: 
     print "What weapon would you like to use?" 
     if weapondict["s1"] == None: 
       print "Error #1: No weapons in the backpack. Contact me (Karatepig) at /hashed out for security/ and make me aware of this error." 
       print "I can return you to the beginning of this checkpoint or I can end the game. Type /return/ to return or /end/ to end." 
       er1=raw_input() 
       if er1.lower() == "end": 
         import sys 
         sys.exit() 
       elif er1.lower() == "return": 
         return None 
       else: 
         print "Sorry, I don't understand." 
         er1d() 
     for weapon in ['s1','s2','s3','s4','s5','s6','s7','s8']: 
      if weapondict[weapon]: 
       print("The weapon {} is available".format(weapondict[weapon])) 
     # as a side note, this can probably also be: 
     ## for weapon in weapondict.values(): 
     ##  print("The weapon {} is available".format(weapon)) 
     # but that depends on what weapondict looks like! 
     # It should be easy to expand to "types" of weapons, as well 
     # using something e.g. 
     ## weapondict = {"Rusty Sword":Sword(dmg=3), "Sharpened Spear":Spear(dmg=7)} 
     # and testing for type(Sword) or type(Spear) based on player class or etc. 
     # but you'd need to build classes for this to work, e.g. 
     ## class Weapon(object): 
     ##  def __init__(self,dmg=1): 
     ##   self.dmg = dmg 
     ## 
     ## class Sword(Weapon): 
     ##  self.type = "Sword" 
     ##  self.dmgType = "Slashing" 
     ## 
     ## class Spear(Weapon): 
     ##  self.type = "Spear" 
     ##  self.dmgType = "Thrusting" 
     # then you can have slashing do more damage to lightly armored targets and 
     # thrusting do more damage to heavily armored targets and etc. Even writing 
     # methods to attack characters based on their equipped weapons. This is a 
     # PRIME example of where OOP will get you big results fast! 

     weapon=raw_input() 
     if weapon.lower() not in weapondict.values(): 
      print "Sorry, I don't understand that.\n\n" 
      continue 

     print("You have selected the {}".format(weapon)) 
     swepd1 = raw_input("Is that what you want? ") 
     if swepd1.lower() in ("y","yes"): swep = weapon 

Если у вас есть какие-либо вопросы, не стесняйтесь спрашивать. Я на самом деле не проверял это, поэтому синтаксические ошибки могут изобиловать. Однако я уверен, что он работает по назначению. В качестве примечания - где weapondict? Это не в вашем коде нигде, и вполне вероятно, что эта функция не сможет его увидеть (если вы не определили ее ранее как global weapondict.)

Смежные вопросы