2017-01-07 4 views
-2

У меня возникли проблемы с использованием функций в python. Я начинающий, поэтому я создаю этот любопытный лабиринт, как игру, и хочу использовать функции, чтобы пользователь мог вернуться в предыдущие местоположения, если захочет. Проблема в том, что весь код после «def sec2():» не запускается и полностью пропускает этот блок кода. Поэтому, если пользователь должен был запустить программу и выбрать влево, программа заканчивается словами «Ах, неважно, помните эти цифры», никогда не запрашивая у пользователя ничего или ничего не печатая из sec2. Я считаю, что мои проблемы могут возникать с отступом. Если кто-нибудь знает, почему код под моими функциями не выполняется, пожалуйста, дайте мне знать! Большое спасибо!Определение функций в python - блок кода не запускается

print ("********") 
print ("Hey there soldier. This is General Chris.") 
print ("I understand you are in quite the situation!") 
print ("Just 4 hours ago, your patrol was ambushed by ISIS...You may not rememeber much after being knocked unconscious!") 
name = input('Whats your name, soldier?') 
print ("********") 
print ("Alright, here's the deal",name) 
print ("You are now being held hostage in an encampment near Soran, Iraq.") 
print ("Unfortunately for you, our hackers have recieved intel that your captors plan on executing you in just two hours.") 
print ("You dont have long to make your escape! Get moving fast!") 

def sec1(): 
    print ("********") 
    print ("You have two doors in front of you. Do you choose the door on the left or right?") 
    room1 = input('Type L or R and hit Enter.') 

    if room1 == "L": 
     print ("********") 
     print ("Good choice",name) 
     print ("Whats this? A slip of paper says '8642' on it...Could it mean something?") 
     print ("Ah, nevermind! Remember those numbers!") 

     def sec2(): 
      print ("********") 
      print ("Now you have a choice between crawling into the cieling, or using the door!") 
      room2 = input('Type C for cieling or D for door, and hit Enter!') 

      if room2 == "C": 
       print ("********") 
       print ("Sure is dark up here in the ducts!") 
       print ("Stay quiet, and move very slowly.") 

       def ductoptionroom(): 
        print ("Do you want to continue into the ducts or retreat?") 
        ductoption = input('Type C or R and hit Enter!') 

        if ductoption == "C": 
         print ("You are continuing into the ducts!") 

        elif ductoption == "R": 
         sec2() 

        else: 
         print ("Focus on the mission!") 



      elif room2 == "D": 
       print ("********") 
       print ("You slowly turn the door knob and see a guard standing there...He doesnt notice you!") 
       print ("Look, theres a piece of rope on the ground! You could use this to strangle the guard!") 

       def guardkillroom(): 
        print ("Do you want to try and kill the guard so you can continue on your escape?") 
        guardkill = input ('Type K for kill or R for retreat and hit Enter!') 

        if guardkill == "K": 
         print ("********") 
         print ("You sneak behind the unsuspecting guard and quickly pull the rope over his neck!") 
         print ("You've strangled the guard! Now you can continue on your mission!") 

        elif guardkill == "R": 
         guardkillroom() 

        else: 
         print ("We dont have all day!") 
         guardkillroom() 

      else: 
       print ("Focus soldier!") 
       room2() 



    elif room1 == "R": 
     print ("********") 
     print ("Uh oh. Two guards are in this room. This seems dangerous.") 
     print ("Do you want to retreat or coninue?") 
     roomr = input('Type R or C and hit enter.') 

     if roomr == "R": 
      print ("********") 
      print ("Good choice!") 
      sec1() 

     elif roomr == "C": 
      print ("********") 
      print ("You continue and are spotted by a guard.") 
      print ("***MIISSION FAILED***") 

     def gameover1(): 
      print ("Do you want to retry?") 
      retry1 = input("Type Y or N and hit enter!") 

      if retry1 == "Y": 
       sec1() 

      elif retry1 == "N": 
       print ("********") 
       print ("Thanks for playing!") 

      else: 
       gameover1() 
sec1() 
+1

Почему вы определяете 'sec2' внутри' sec1'? Пожалуйста, сохраните все функции на уровне модуля. – Matthias

+0

Возможный дубликат [Вызов функции модуля из строки с именем функции в Python] (https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a- строка-с-функции-имя-в-питон) – Chris

ответ

1

Похоже, вы только когда-либо определить sec2, и вы никогда не называют. Когда вы делаете что-то вроде def myfunc(), он просто сообщает python, что должен произойти, когда эта функция вызывается. Код никогда не будет запущен до тех пор, пока вы не запустите myfunc() из другого места в коде. И единственное место sec2 называется рекурсивно внутри sec2 (если игрок решает отступить от протоки)

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

print ("Ah, nevermind! Remember those numbers!") 

    def sec2(): 
     .... 


    elif room2 == "D": 
     sec2() 

Дополнительно после sec2 определяется внутри sec1, что означает sec2 только может когда-либо назвать внутри sec1, а также. Я подозреваю, что это было не то, что было предназначено (хотя я мог ошибаться). Чтобы исправить это, вы можете сделать следующее:

def sec2(): 
    ... 
def sec1(): 
    ... #All the same code as before except for the sec2 definition 

sec1() 
Смежные вопросы