2016-01-10 4 views
-3

Я написал свой код как обычно, но по какой-то причине, когда он доходит до точки, прежде чем def jscript() он просто останавливается. Никаких ошибок или чего-либо, что он просто останавливает. Может кто-то помочь мне PLS. Извините за весь код ... Вот и весь мой код, чтобы попробовать, и тогда вы поймете, что происходит. Я думаю, что копия и вставка испортили отступы.Мой код внезапно останавливается ...?

def script(): 
      Wins = 0 
      Fails = 0 
      Energy = 20 
      Fuel = 40 
      Oxygen = 30 
      Coins = 10 
      Life = 100 
      AlienLife = 250 
      global Energy 
      global Fuel 
      global Oxygen 
      global Coins 
      global Life 
      global Wins 
      global Fails 

      time.sleep(5) 
     firstName = input("Hello! What is your first name? ") 
     surnameName = input(" And what is your surname? ") 
     fullName = firstName + " " + surnameName 
     print ("Ok then. Welcome,",fullName,"to the Age Of Space! Here you will have to drive your spaceship victoriously and survive all enemy threats. Your mission is to free Earth from the alien abduction!") 
     time.sleep(7) 
     print("Btw good luck in defeating the alien king! ;)") 
     time.sleep(3) 
     print("Your spaceship will take off in 5...") 
     time.sleep(2) 
     print("4...") 
     time.sleep(1) 
     print("3...") 
     time.sleep(1) 
     print("2...") 
     time.sleep(1) 
     print("1...") 
     time.sleep(2) 
     print ("BLAST OFF!!!") 
     time.sleep(5) 
     print("You are now in the depths of space. Commander please ensure that you keep safe during your journey. Good luck!") 
     time.sleep(2) 
     sleep = input("Commander, would you like to sleep now? If yes then we can take out your bed. ") 
     if sleep == "yes": 
      Energy = Energy + 5 
      print("We have taken out your bed. The spaceship is on autopilot and you may now sleep.") 
      time.sleep(4) 
      print("2 weeks later...") 
     else: 
      Energy = Energy - 5 
      print("Ok. It is all your choice. BUT you WILL lose energy. Lets carry on with the journey. You have",Energy,"energy remaining.") 
      time.sleep(4) 
     print("Commander, you have been extremely successful so far. Well done and keep it up!") 
     time.sleep(6) 
     direction = input("Oh no Sir! There is trouble ahead! Please make your decision quick. It's a matter of life and death. It is also a matter of chance! There are many asteroids ahead. You may either go forwards, backwards, left or right. Make your decision...before it's too late! ") 
     if direction == "left": 
      Coins = Coins + 15 
      Fuel = Fuel - 15 
      while True: 
       print ("You have managed to pass the asteroids, you may now carry on. You have",Fuel,"fuel left.") 
       break 
       continue 
     elif direction == "backwards": 
      print("You have retreated and gone back to Earth. You will have to start your mission all over again.") 
      time.sleep(2.5) 
      print("The game will now restart.") 
      time.sleep(2) 
      print("Please wait...\n"*3) 
      time.sleep(5) 
      keep_playing = True 
      while True: 
       script() 
     elif direction == "forwards": 
      Fails = Fails + 1 
      print("You have crashed and passed away. Your bravery will always be remembered even if you did fail terribly. You have failed",Fails,"times.") 
      time.sleep(3) 
      ans = input("Do you want to play again? ") 
      if ans == "yes": 
       time.sleep(6) 
       script() 
      else: 
       print("Our Earth is now an alien world...") 
     else: 
      Fuel = Fuel - 10 
      Coins = Coins + 15 
      print("You have landed on a planet and have",Fuel,"fuel left.") 
      time.sleep(1) 
      def myscript(): 
       Fuel = 30 
       Oxygen = 30 
       Coins = 25 
       print("What do you want to buy? You have currently",Coins,"coins and",Fuel,"fuel.") 
       print ("You have a choice between the following and may only buy one:") 
       time.sleep(1)  
       pistol = 20 
       print("A pistol for 20 coins") 
       time.sleep(1) 
       costfuel = 10 
       print("15 fuel for 10 coins") 
       time.sleep(1) 
       shotgun = 40 
       print("A shotgun for 40 coins") 
       time.sleep(1) 
       costoxygen = 10 
       print("10 oxygen for 10 coins") 
       time.sleep(1) 
       costlife = 50 
       print("or 5 life for 50 coins") 
       time.sleep(1) 
       choose = input("You may now choose which of the following you want - please type it in e.g fuel. ") 
       if choose == "pistol": 
        while Coins < pistol: 
         print ("You cannot buy this as you do not have enough money. Please type in something else.") 
         time.sleep(4) 
         myscript() 
         break 
        else: 
         Coins = Coins - 20 
         print ("Thank you for purchasing the pistol! You have",Coins,"coins remaining.") 
       elif choose == "fuel": 
        while Coins < costfuel: 
         print ("You cannot buy this as you do not have enough money. Please type in something else.") 
         time.sleep(4) 
         global Coins 
         myscript() 
         break 
        else: 
         Coins = Coins - 10 
         Fuel = Fuel + 15 
         print ("Thank you for purchasing the fuel! You have",Fuel,"fuel remaining and",Coins,"coins remaining.") 
       elif choose == "shotgun": 
        while Coins < shotgun: 
         print ("You cannot buy this as you do not have enough money. Please type in something else.") 
         time.sleep(4) 
         global Coins 
         global Fuel 
         Coins = 15 
         Fuel = 45 
         myscript() 
         break 
        else: 
         Coins = Coins - 40 
         print ("Thank you for purchasing the shotgun! You have",Coins,"coins remaining") 
       elif choose == "oxygen": 
        while Coins < costoxygen: 
         print ("You cannot buy this as you do not have enough money. Please type in something else.") 
         time.sleep(4) 
         global Coins 
         myscript() 
         break 
        else: 
         Coins = Coins - 10 
         Oxygen = Oxygen + 10 
         print ("Thank you for purchasing the oxygen! You have",Coins,"coins remaining and",Oxygen,"oxygen remaining.") 
         global Coins 
         Coins = 15 
         global Oxygen 
         Oxygen = 40 
       else: 
        while Coins < costlife: 
         print ("You cannot buy this as you do not have enough money. Please type in something else.") 
         time.sleep(4) 
         myscript() 
         break 
        else: 
         Coins = Coins - 50 
         print ("Thank you for purchasing more life! You have",Coins,"coins remaining and",Life,"life remaining!") 
      myscript() 
     time.sleep(3.5) 
     prin = input("Well done Commander! Bravo! You are doing excellent! Would you like to eat? ") 
     if prin == "yes": 
      Oxygen = Oxygen - 10 
      print ("There is a lot of food in the cupboard please help yourself.") 
     else: 
      print ("Very well, hope you don't get hungry Sir.") 
      time.sleep(2.5) 
     papy = input("Would you like to go to sleep commander? ") 
     if papy == "yes": 
      Energy = Energy + 5 
      print("Hope you have a great nap and fill yourself with enrgy Sir! Your bed has been taken out and you may now sleep.") 
      time.sleep(6) 
      print("15 hours later...") 
      time.sleep(3.5) 
      print("Sir! Sorry to interfere your sleep but you have landed on a planet!") 
      def minescript(): 
       global Coins 
       global Oxygen 
       global Fuel 
       print("What do you want to buy? You have currently",Coins,"coins and",Fuel,"fuel.") 
       print ("You have a choice between the following and may only buy one:") 
       time.sleep(1)  
       pistol = 20 
       print("A pistol for 20 coins") 
       time.sleep(1) 
       costfuel = 10 
       print("15 fuel for 10 coins") 
       time.sleep(1) 
       shotgun = 40 
       print("A shotgun for 40 coins") 
       time.sleep(1) 
       costoxygen = 10 
       print("10 oxygen for 10 coins") 
       time.sleep(1) 
       choose = input("You may now choose which of the following you want - please type it in e.g fuel. If you do not have enough money to buy anything type in 'nothing'. ") 
       if choose == "pistol": 
        while Coins < pistol: 
         print ("You cannot buy this as you do not have enough money. Please type in something else.") 
         time.sleep(4) 
         minescript() 
         break 
        else: 
         Coins = Coins - 20 
         print ("Thank you for purchasing the pistol! You have",Coins,"coins remaining.") 
       elif choose == "fuel": 
        while Coins < costfuel: 
         print ("You cannot buy this as you do not have enough money. Please type in something else.") 
         time.sleep(4) 
         myscript() 
         break 
        else: 
         Coins = Coins - 10 
         Fuel = Fuel + 15 
         print ("Thank you for purchasing the fuel! You have",Fuel,"fuel remaining and",Coins,"coins remaining.") 
       elif choose == "shotgun": 
        while Coins < shotgun: 
         print ("You cannot buy this as you do not have enough money. Please type in something else.") 
         time.sleep(4) 
         minescript() 
         break 
        else: 
         Coins = Coins - 40 
         print ("Thank you for purchasing the shotgun! You have",Coins,"coins remaining") 
       elif choose == "oxygen": 
        while Coins < costoxygen: 
         print ("You cannot buy this as you do not have enough money. Please type in something else.") 
         time.sleep(4) 
         minescript() 
         break 
        else: 
         Coins = Coins - 10 
         Oxygen = Oxygen + 10 
         print ("Thank you for purchasing the oxygen! You have",Coins,"coins remaining and",Oxygen,"oxygen remaining.") 
       else:   
         print ("Hope you find something to buy next time :)") 
      minescript()  
     else: 
      Energy = Energy - 10 
      print("Very well Sir. You have",Energy,"energy remaining now.") 
     time.sleep(4) 
     print("Now you will see a map of where you are and how close you are to the alien palace.") 
     time.sleep(2) 
     print("Please wait...") 
     time.sleep(2) 
     print("Please wait...") 
     time.sleep(2) 
     print("Please wait...") 
     time.sleep(8) 
     print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("ZZZZZZZZZZZZZZZZZZZZZ00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("ZZZZZZZZZZZZZZZZZZZZZ00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("     ZZ00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("     ZZ00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("     ZZ00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("     ZZ00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("     ZZ00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("     ZZ000000000000000000MMMM000000000000000000000000PPPPPPPPPP0000000000000000000000000000000000000000000000-00000000-0000000000000000000") 
     print("     ZZ000000000000000000MMMM000000000000000000000000P  P000000000000000000000000000000000000000000000- -000000- -000000000000000000") 
     print("     ZZ000000000000000000MMMM00000000MMM0000000000000P PLANET P00000000000000000000000000000000000000000000- -0000- -00000000000000000") 
     print("  EARTH  ZZ0000000000000000000---------00MMM0000000000000P  P000000000000000000000000000000000*0000000000- -000- -00000 **  ** 0") 
     print("(where you started)ZZ--------------------000MMM0--------------00000PPPPPPPPPP0000000000000000000000000000000*****00000000- a -000- -00000 ..  .. 0") 
     print("     ZZ00000000000000000000000MMM00000000000000-0000000000000000000000000IIIII0000000000000000*****00000000- l -000- -00000  oo 0") 
     print("     ZZ000000000000000000000000000000MMM0000000--------------------------I U I00000000000000000000000000000- i -000- -00000   0") 
     print("     ZZ000000000000000000000MMMMM0000000000000000000000000000000000000000IIIII00000000000000000000000000000- e -000- -00000 (_______) 0") 
     print("     ZZ000000000000000000000MMMMM00000000000000000000000000000000000000000000000000000000000000000000000000- n -000- -00000   0") 
     print("     ZZ000000000000000000000MMMMM0000000000000000000000000000000000000000000000000000000000000000000*000000- -000- p -00000000000000000") 
     print("     ZZ0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*****0000- -000- a -00000000000000000") 
     print("     ZZ00000000000000000000000000000000000PPPPPPPPPP0000000000000000000000000000000000000000000000*****0000- -000- l -00000000000000000") 
     print("ZZZZZZZZZZZZZZZZZZZZZ00000000000000000000000000000000000P  P0000000000000000000000000000000000000000000000000000000- -000- a -00000000000000000") 
     print("ZZZZZZZZZZZZZZZZZZZZZ00000000000000000000000000000000000P PLANET P0000000000000000000000000000000000000000000000000000000- -000- c -00000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000P  P0000000000000000000000000000000000000000000000000000000- -000- e -00000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000P  P00000000000000000000000000000000000000000000000000000000- -00000- -000000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000PPPPPPPPPP000000000000000000000000000000000000000000000000000000000--0000000-0000000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") 
     time.sleep(5) 
     print("MMM = asteroids") 
     time.sleep(1.5) 
     print("U = where you are") 
     time.sleep(1.5) 
     print("---- = path") 
     time.sleep(1.5) 
     print("***** = alien security/alien guards ") 
     time.sleep(6) 
     print("Please ensure that you have reviewed the map - thank you.") 
     print("Commander, you have progressed extremely well and will be well remembered in history. For your progress you have been awarded 100 extra coins! Please use it wisely if you get a chance. Remember you have",Life,"lives and the alien king has",AlienLife,"lives!") 
     global Coins 
     Coins = Coins + 100 
     print("You now have",Coins,"coins.") 
     p = input("You have " + str(Energy) + " energy left commander, would you like to go to sleep? ") 
     if p == "yes": 
      print("Hope you have a great sleep THIS time :)") 
      Energy = Energy + 2 
     else: 
      print("Very well.") 
      Energy = Energy - 5 
     if Energy == 0: 
      print("You have run out of energy master! You must retreat now!") 
      time.sleep(1) 
      print ("Your mission is over. You have travelled back to Earth on autopilot. You were too tired to carry on.") 
      time.sleep(2) 
      print ("The game will now restart.") 
      time.sleep(4) 
      script() 
     else: 
      Fuel = Fuel - 5 
      print("You have",Energy,"energy and",Fuel,"fuel left.") 
      print("You are doing very well. Soon you will have to battle the alien guards so be prepared to loose some lives :). No pressure.") 
      time.sleep(3) 
      print("After an hour...") 
      time.sleep(3) 
      Fuel = Fuel - 5 
      if Energy == 0: 
       print("You have run out of energy master! You must retreat now!") 
       time.sleep(1) 
       print ("Your mission is over. You have travelled back to Earth on autopilot. You were too tired to carry on.") 
       time.sleep(2) 
       print ("The game will now restart.") 
       time.sleep(4) 
       script() 
      else: 
       print("Sir! The ship has broken down. You have to go outside to fix it. As a consequence you will loose quite a bit of oxygen. You have",Oxygen,"oxygen left and",Energy,"energy left. Please make a choice between the following:") 
       time.sleep(2) 
       print("Repair fully - result in 10 oxygen loss and 10 energy loss.") 
       time.sleep(2) 
       print("Repair half - result in 5 oxygen loss and 5 energy loss. Then you will be able to finish it off the next day after sleeping.") 
       time.sleep(2) 
       print("Do not repair now - result in no loss of energy and oxygen but you will not be able to finish the repair the next day either.") 
     def jscript(): 
      global Coins 
      global Oxygen 
      global Fuel 
      repair = input("Please type in your choice. E.g. full or half or not now. ") 
      if repair == "full": 
       while Energy < 10: 
        print("You cannot carry out this option, sorry.") 
        time.sleep(3) 
        jscript() 
        break 
       else: 
        Oxygen = Oxygen - 10 
        Energy = Energy - 10 
        print("The repair has been successful. You now have",Fuel,"fuel",Oxygen,"oxygen and",Coins,"remaining!") 
      elif repair == "half": 
       while Energy < 5: 
        print("You cannot carry out this option, sorry.") 
        time.sleep(3) 
        jscript() 
        break 
       else: 
        Oxygen = Oxygen - 5 
        Energy = Energy - 5 
        print("The half repair has been successful. You now have",Fuel,"fuel",Oxygen,"oxygen and",Coins,"remaining!") 
        time.sleep(2) 
        print("Commander hopefully this will not seem too aggressive to you, but I think you HAVE to sleep now. The beds are ready so take a rest...") 
        Energy = Energy + 6 
        time.sleep(3) 
        print("The next day...") 
        time.sleep(3) 
        print("Congarats! The rest of the spaceship has been repaired successfully without any loss! ;)") 
      else: 
       print("There will be no repair done.") 
       time.sleep(2.5) 
       print("The next day...") 
       time.sleep(3.5) 
       foo = ['a'] * 65 + ['b'] * 35 
       an = random.choice(foo) 
       if an == "a": 
        print("hi") 
       else: 
        print("SHing CHing") 
    script() 
+1

Пожалуйста, исправьте свой отступ кода, кажется неправильным – Arman

+0

может показать мне, пожалуйста, – wacraby

+0

, кстати, это еще не конец кода, но я не поставил его – wacraby

ответ

1

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

  • Внедрение печати и сон функции - Вводя функцию на верхнем уровне, чтобы напечатать сообщение и сон на некоторое время уменьшит ваш код резко.
  • Использование "Welcome {} to the Age Of Space".format(fullname) упростить обработку строки - Это в сочетании с предыдущим предложением может привести к следующей функции:

    def output_message(message, sleep_time): 
        """Outputs a message, followed by a sleep period.""" 
    
        print(message) 
        time.sleep(sleep_time) 
    

    , который затем может быть использован как:

    output_message("Welcome {}, to the Age Of Space!".format(fullName), 7) 
    output_message("Good luck in defeating the alien king! ;)", 3) 
    output_message("Your spaceship will take off in 5...", 2) 
    output_message("4...", 1) 
    output_message("3...", 1) 
    output_message("2...", 1) 
    
  • Собирать функции при запуске файла - Несмотря на то, что законно определять функции практически на любом уровне в Python, это настоятельно советует d для определения всех функций в начале вашего файла. Другими словами, что-то вроде следующего:

    import time 
    
    def output_message(message, sleep_time): 
        """My docstring.""" 
        ... code as before ... 
    
    
    def script(): 
        ... 
        code of script() 
        ... 
    
    def myscript(): 
        ... code of myscript ... 
    
    def main(): 
        while True: 
         start_mission() 
         # Ask if user wants to restart game 
         restart = input("Do you want to restart game? ") 
    
         if restart == "no": 
          break 
    
    
    if __name__ == "__main__": 
        main() 
    

    Как вы можете видеть, все функции начинается в начале строки, и это нормально, до тех пор, пока вы не определяет методы класса, которые были бы на один уровень отступа далее в .

    PS! Наконечник обмена пакетами: После вставки текста в поле редактирования здесь, на сайте Stack Exchange, отметьте все и нажмите Ctrl-K, чтобы правильно отстудить код.

  • Избегайте последовательную рекурсивная функцию вызова - То есть вместо вызова script() изнутри def script(), вы должны позволить сценарий до конца, а затем вызвать его в другой раз, если пользователь выбирает для перезагрузки. Эта структура изображена в предыдущем блоке кода.

    Аналогичную структуру следует применять при вызове minescript(), myscript() и, возможно, jscript(). Все они, кстати, плохо названы и не отображают то, что на самом деле происходит.Также кажется, что minescript() и myscript() очень похожи, и их можно назвать чем-то вроде buy_stuff().

  • Ошибка: Вы не называйте jscript() вне jscript() и неправильно уровень отступа - Все остальные внутренние функции у вас есть, как minescript() и myscript следует этой схеме:

    if something: 
        ... 
    elif something else: 
        ... 
    else 
        ... 
        def aFunction(): 
         ... 
        aFunction() 
    if yet_another_condition: 
        ... 
    

    Но для jscript() вы переместили отступ на два уровня, и вы делаете не после того, как определение jscript().

  • Избегайте странный цикл при покупке вещи - У вас есть странное понятие петель, связанных с внутренними функциями, как этот упрощенный вариант minescript():

def minescript(): 
     global Coins 
     global Oxygen 
     global Fuel 
     print("What do you want to buy? You have currently",Coins,"coins and",Fuel,"fuel.") 
     output_message("You have a choice between the following and may only buy one:", 1) 
     pistol = 20 
     output_message("A pistol for 20 coins", 1) 
     costfuel = 10 
     print("15 fuel for 10 coins") 
     choose = input("You may now choose which of the following you want - please type it in e.g fuel. If you do not have enough money to buy anything type in 'nothing'. ") 
     if choose == "pistol": 
      while Coins < pistol: 
       output_message("You cannot buy this as you do not have enough money. Please type in something else.", 4) 
       minescript() 
       break 
      else: 
       Coins = Coins - 20 
       print("Thank you for purchasing the pistol! You have",Coins,"coins remaining.") 
     elif choose == "fuel": 
      while Coins < costfuel: 
       print ("You cannot buy this as you do not have enough money. Please type in something else.") 
       time.sleep(4) 
       myscript() 
       break 
      else: 
       Coins = Coins - 10 
       Fuel = Fuel + 15 
       print ("Thank you for purchasing the fuel! You have",Fuel,"fuel remaining and",Coins,"coins remaining.") 
     else:   
       print ("Hope you find something to buy next time :)") 
    minescript() 

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

def minescript(): 
    global Coins 
    global Oxygen 
    global Fuel 
    print("What do you want to buy? You have currently",Coins,"coins and",Fuel,"fuel.") 
    output_message("You have a choice between the following and may only buy one:", 1) 
    pistol = 20 
    output_message("A pistol for 20 coins", 1) 
    costfuel = 10 
    print("15 fuel for 10 coins") 
    while True: 
     choose = input("You may now choose which of the following you want - please type it in e.g fuel. If you do not have enough money to buy anything type in 'nothing'. ") 
     if choose == "pistol": 
      if Coins < pistol: 
       output_message("You cannot buy this as you do not have enough money. Please type in something else.", 4) 
      else: 
       Coins = Coins - pistol 
       print("Thank you for purchasing the pistol! You have",Coins,"coins remaining.") 
       break 
     elif choose == "fuel": 
      if Coins < costfuel: 
       output_message("You cannot buy this as you do not have enough money. Please type in something else.", 4) 
     else: 
      Coins = Coins - costfuel 
      Fuel = Fuel + 15 
      print ("Thank you for purchasing the fuel! You have",Fuel,"fuel remaining and",Coins,"coins remaining.") 
      break 
    else:   
      print ("Hope you find something to buy next time :)") 
      break 
minescript() 

Еще лучше вариант будет держать вещи доступны для покупки в списке с соответствующей ценой и использовать это, чтобы упростить функцию еще дальше.

def buy_stuff(items): 
    global Coins 
    global Oxygen 
    global Fuel 
    print("What do you want to buy? You have {} Coins, and {} fuel".format(Coins, Fuel)) 
    output_message("You have a choice between the following and may only buy one:", 1) 
    for item in items: 
     print(" {} : {} coins".format(item, items[item])) 

    while True: 
     choice = input("Type item you want to purchase or 'nothing'") 
     if choice in items: 
      if items[choice] > Coins: 
       output_message("You don't have enough money. Try something else.", 4) 
      else: 
       Coins = Coins - items[choice] 
       print("You bought: {}, and have {} coins left.".format(choice, Coins)) 
       break 
     elif choose == "nothing": 
      print ("Hope you find something to buy next time :)")     break 
     else:   
      print("Couldn't find that item. Use 'nothing' if you don't want to buy anything.") 

store_items = { 
    'pistol': 20, 
    'fuel': 15, 
    'energy': 20 
} 
buy_stuff(store_items) 

Code is untested, but you should get the gist of it. And it can be adapted to changing the different variables by utilizing tuples or similar. 

Надеюсь, эти советы должны помочь вам получить на пути к решению ваших проблем, и упростить код довольно радикально. В заключение обратите внимание, что вам следует также избегать использования глобальных таблиц и, возможно, упрощать некоторые сообщения или анализировать предопределения некоторых из более крупных текстовых частей, чтобы еще больше укрепить фокус на логике игры в вашем коде вместо «шумных» всех текстовые сообщения, которые в настоящее время стоят.

+0

Извините, что спросите об этом, но что вы подразумеваете под этим именем Вы не вызываете jscript() вне jscript() и что вы не вызываете jscript() после определения? – wacraby

+0

@wacraby ser выдержка кода в моем ответе, там определение функции 'def minescript():' с кодом следует вызов 'minescript()'. Определение jscript является ** не **, за которым следует вызов ... – holroy

+0

Я сделал то же самое с jscript, как с minescript. Извините, я не понимаю. – wacraby

1

Я собираюсь предположить, что это то, что вы пытаетесь получить. Вы не должны определять функцию внутри if-else statement. Вы просто должны это назвать.

else: 
    print("Sir! The ship has broken down. You have to go outside to fix it. As a consequence you will loose quite a bit of oxygen. You have",Oxygen,"oxygen left and",Energy,"energy left. Please make a choice between the following:") 
    time.sleep(2) 
    print("Repair fully - result in 10 oxygen loss and 10 energy loss.") 
    time.sleep(2) 
    print("Repair half - result in 5 oxygen loss and 5 energy loss. Then you will be able to finish it off the next day after sleeping.") 
    time.sleep(2) 
    print("Do not repair now - result in no loss of energy and oxygen but you will not be able to finish the repair the next day either.")* This is where the code stops 
    jscript() 

def jscript(): 
    global Coins 
    global Oxygen 
    global Fuel 
    repair = input("Please type in your choice. E.g. full or half or not now. ") 
    if repair == "full": 
     while Energy < 10: 
      print("You cannot carry out this option, sorry.") 
      time.sleep(3) 
      jscript() 
      break 
    else: 
     Oxygen = Oxygen - 10 
     Energy = Energy - 10 
     print("The repair has been successful. You now have",Fuel,"fuel",Oxygen,"oxygen and",Coins,"remaining!") 

Кроме того, почему вы называете функцию внутри себя, а затем сделать перерыв это бессмысленно, а затем вы делаете то время как внешний вид, что перерывы после завершения один раз. Удалите все, что бессмысленно и ничего не делает, просто используйте другой if.

def jscript(): 
    global Coins 
    global Oxygen 
    global Fuel 
    repair = input("Please type in your choice. E.g. full or half or not now. ") 
    if repair == "full": 
     if Energy < 10: 
      print("You cannot carry out this option, sorry.") 
      time.sleep(3) 
     else: 
      break 
    else: 
     Oxygen = Oxygen - 10 
     Energy = Energy - 10 
     print("The repair has been successful. You now have",Fuel,"fuel",Oxygen,"oxygen and",Coins,"remaining!") 
+0

попробовал, но он все еще не работает :( – wacraby

+0

Не могли бы вы объяснить, что должно было произойти и опубликовать весь код, пожалуйста, –

+0

вы получили это право После того, как вы отделили def() и все после того, как он все еще не работает. Когда я запускаю его, последнее сообщение появляется там, где код останавливается.Так вот так: – wacraby

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