Значение, определенное в одной функции, недоступно в другой - PullRequest
0 голосов
/ 31 мая 2018

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

Итак, мы с дочерью пишем игру вместе.Я работал над некоторыми основами программирования, пока она занимается творчеством.У меня есть функция, где пользователь выбирает «класс», который назначает базовые значения для определенных аспектов и возвращает их в качестве переменной.После других постов я сначала попытался использовать функцию return , но это не сработало, поэтому я попробовал функцию global .Это позволяет программе использовать переменную, чтобы просто напечатать ее вне функции, но когда другая функция пытается использовать переменную, она появляется как не переменная, на которую ссылаются перед присваиванием.

     import random
     import time
     #these were another attempt at finding a way to make the classes
     #available to other functions
     combat = 0
     strength = 0 
     agility = 0
     magic = 0
     intelligence = 0
     def chose_class():
         #I tried return "each characteristic" at the end, but it wouldn't 
         #even print out the returned value
         global strength
         global combat
         global agility
         global magic
         global intelligence
         health = 10
         print("Chose your class:")
         print("Warrior: 1")
         print("Wizard: 2")
         print("Philosopher: 3")
         print("Thief: 4")
         print("Help: 5")
         dog1 = int(input(":"))
         if dog1 ==1:
             strength = 7
             combat = 7
             agility = 5
             stealth = 3
             magic = 1
             intelligence = 1
         elif dog1 == 2:
             strength = 3
             combat = 1
             agility = 3
             stealth = 3
             magic = 8
             intelligence = 6
         elif dog1 == 3: 
             strength = 3
             combat = 1
             agility = 3
             stealth = 3
             magic = 2
             intelligence = 8
         elif dog1 == 4:
             strength = 2
             combat = 4
             agility = 6
             stealth = 8 
             magic = 1
             intelligence = 6
         elif dog1 == 5:
             print("Warrior Dog:")
             print("    Warrior Dogs possess great strength and combat                                    ability")
             print("    they have medium agility, but low stealth, magic and")
             print("    intelligence.")
             print("\n"*2)
             print("Wizard Dog:")
             print("    Wizard Dogs have low strength, combat, and agility,")
             print("    they have medium stealth and high magic capabilities.")
             print("\n"*2)
             print("Philosopher Dog:")
             print("    Philosopher Dogs are highly intelligent, while they")
             print("    have low strength, they have medium combat ability.")
             print("    Their agility, stealth, and magic start low but can")
             print(" rapidly improve by finding hidden objects on quests.")  
             print("\n"*2)
             print("Thief Dogs")
             print("    Thief Dogs have high agility and stealth, as well as")
             print("    average intelligence and combat. They have low combat,")
             print("    magic, and strength.")
         else:
             chose_class()
     def room17():
         print("**Description**")
         print("Do you want to fight the cat guard or sneak past it?")
         print("Fight: 1")
         print("Sneak Past: 2")
         choice17 = str(input(":"))
         if "1" in choice17:
             fight17 = random.randint(0,5)
             combat17 = combat * fight17
             if combat17 <= 20:
                 print("You were successful")
                 combat = combat + 1
             else:
                 print("You lost the fight and had to retreat")
                 health = health - 1
                 room1()
         else:
             sneak17 = random.randint(0,5)
             stealth17 = sneak17 * stealth
             if stealth17 <= 20:
                 print("You snuck past the guard")
                 stealth = stealth + 1
             else:
                 print("The guard caught you, he attacks and you have to retreat")
                 health = health - 2
                 stealth = stealth - 1
                 room1()
     chose_class()
     # this was just to see if the value was returned
     print("Combat:", combat)
     # I'm jumping to the first combat event to try to test the program
     room17()

Хорошо, этого должно быть достаточно, чтобы продемонстрировать проблему.Я полностью самоучка, поэтому я уверен, что есть множество стилистических проблем, с которыми я очень рад получить помощь.Но если кто-то может помочь с тем, почему переменная "battle" возвращается из "def selected_class ()" в команду печати, но затем не назначается в "def room17 ()", я был бы очень признателен.

...