2014-12-06 30 views
-2

我很困惑如何製作條件語句。我似乎無法弄清楚。在下面的示例中,我希望拍攝輸入僅在用戶選擇在這種情況下在遊戲的早期階段才起作用。和刀子一樣等等。如何在Python中創建條件語句?

def chap4(): 
print "You feel around the room.\n" 
time.sleep(3) 
print "You find a small chest...\n" 
time.sleep(3) 
print "You open the chest...\n" 
time.sleep(2) 
print "[pickaxe, shovel, lighter, axe, 9mm(0), knife]\n" 
    while (True): 
     chest = raw_input("What will you take?: ") 
     if chest == "pickaxe": 
      print "You take the pickaxe" 
      break 
     elif chest == "shovel": 
      print "You take the shovel" 
      break 
     elif chest == "lighter": 
      print "You take the axe" 
      break 
     elif chest == "9mm": 
      print "You take the empty 9mm pistol" 
      break 
     elif chest == "knife": 
      print "You take the knife" 
      break 
     elif chest == "axe": 
      print "You take the axe" 
      break 
     else: 
      print "Invalid choice. Try again..." 
chap4() 

def zombie(): 
    print "A zombie is seem in the distance" 
    while (True): 
     attack = raw_input("> ") 
     if attack == "shoot": 
      print "Zombie hp 50/100" 
     elif attack == "stab": 
      print "Zombie hp 70/100" 
     else: 
      print "Invalid input. Try again..." 

所以你可以通過代碼中遇到麻煩告訴...我本來以爲也許我會再拍if語句的if語句中,但我不知道。請幫助,如果你可以...謝謝!

回答

1

我建議把一個conditional if

def chap4(): 
    .... 
    return(chest) 
def zombie() 
    weapon = chap4() 
    if weapon == "9mm": 
     if attack =="shoot": 
      print(...) 
     elif attack =="stab": 
     ... 

等。 所以在zombie()的條件中指定武器。此外,zombie()必須知道的chest變量,所以return(chest)chap4()函數的末尾,並調用chap4()zombie()

編輯:zombie()調用chap4()的時候,它需要所謂的一個變量,在這種情況下,weapon

1

你可以存儲cointain什麼胸這樣的:

chestContainer= {"pickaxe": "pickaxe", "shovel": "shovel", "lighter": "lighter", "9mm(0)": "9mm(0)", "knife": "knife", } 

然後你可以打印這樣的選項:

print chestContainer[chest] 

如果輸入是這樣有效,您可以評估:

if chestContainer[chest] == None: 
    print "Invalid choice. Try again..." 

編輯:

正如user908293說你要救你選擇什麼樣的武器。

weapon = chestCointainer[chest] 
1

條件語句是好的,只要他們去。問題在於你沒有在任何地方保存結果。這樣做

if chest == "pickaxe": 
    print "You take the pickaxe" 
    weapon = "pickaxe" 
elif chest == "shovel": 
    print "You take the shovel" 
    weapon = "shovel" 
etc. 

當用戶選擇一個攻擊模式,你可以檢查他有合適的武器:

if attack == "shoot": 
    if weapon == "9mm": 
    print "Zombie hp 50/100" 
    else: 
    print "you don't have a pistol" 

這裏同樣,印刷可能是不夠的。你會想要跟蹤發生了什麼,我會認爲

+0

當我這樣運行它我得到一個錯誤告訴我武器沒有定義? – 2014-12-07 00:36:55

+1

@ Python-Pygames-help.me這是因爲,正如我在回答中所說的,胸部/ weaspon沒有在'zombie()'中定義,它在'chap4()'中定義。所以你需要在'chap4()'中輸入'return(chest)',並在'zombie()'中調用'chap4()'見我編輯的代碼 – AppliedNumbers 2014-12-07 01:43:33