Python не выходит из функции после того, как это сделано - PullRequest
0 голосов
/ 13 декабря 2018

Я пытаюсь написать игру для своего класса comp-sci.Тем не менее, когда я добираюсь до функции, которая диктует нападение на врага даже после ее завершения, она возвращается к началу, а не продолжает код.(Проигнорируйте бессмысленный цикл for, мне просто нужен один в моем коде) Я перепробовал кучу вещей, но я все еще не могу заставить его работать вообще.

lives = 3
primary = "Rusty Sword"
armor = "Old Armor"
damage = 2
luck = 3
defense = 1
defchance = 3
enemynumber = 0


print("\nYou begin your trek through the dense forest and you stumble accross a skeleton!\nThe skeleton has",enelives1,"lives.\nYou currently have",lives,"lives.")
print("\nInventory:\n"+primary+"-",damage,"Damage\n"+armor+"-",defense,"Defense")
aord = input("\nThe skeleton is coming towards you! Do you attack it or defend first?\n")
aord = aord.lower()
while aord != "attack" and aord != "defend": 
    print("Invalid input")
    print("Would you like to attack or defend?")
    aord = input("\nThe skeleton is coming towards you! Do you attack it or defend first?\n")

def attack1():
    hit = random.randint(1,luck)
    print("In order to attack the skeleton you must correctly guess a number from 1 to",luck+2,".")
    attackguess = int(input())
    guessnumber = 1
    global enelives1
    global lives
    while lives >= 3 and (guessnumber == 1 or guessnumber == 2):
        while guessnumber == 1:
            if attackguess > hit:
                print("Too high. One more chance.")
                guessnumber = 2
            elif attackguess < hit:
                print("Too low. One more chance.")
                guessnumber = 2
            else:
                enelives1 = enelives1 - damage
                print("You hit the skeleton! It now has",enelives1,"lives.")
                guessnumber = 3
            while guessnumber == 2:
                attackguess = int(input())
                if attackguess == hit:
                    enelives1 = enelives1 - damage
                    print("You hit the skeleton! It now has",enelives1,"lives.")
                    guessnumber = 3
                    global aord
                    aord == "defend"
        if lives >= 1 and guessnumber == 2:             
            print("You missed the skeleton! It is now about to swing at you!")
            aord = "defend"
        elif lives < 1:
            print("Oh no! You ran out of lives and died! Press enter to end the program")
            input()
            quit()



while enelives1 >= 1:            
    if aord == "attack":
        attack1()
    elif aord ==  "defend":
        defend1()

Ответы [ 2 ]

0 голосов
/ 13 декабря 2018

Причина, по которой ваша функция не завершается, заключается в том, что цикл while содержит догадку.Если у вас есть второе предположение, и вы угадываете правильно, вы, как и ожидалось, введете оператор if для получения удара и выйдите.Однако, если вы ошиблись во втором предположении, вы оказались в ловушке в цикле while, потому что код предположения по-прежнему равен 2. Таким образом, условие, поддерживающее выполнение цикла while, все еще выполняется.Чтобы исправить отсутствие выхода, если они получают второе предположение неверно, вам нужно изменить значение guessnumber (на что угодно, кроме 1) следующим образом:

while guessnumber == 2:
    attackguess = int(input())
    if attackguess == hit:
        enelives1 = enelives1 - damage
        print("You hit the skeleton! It now has" ,enelives1, "lives.")
        guessnumber = 3
        global aord
        aord == "defend"
    else: 
        guessnumber = 0 #this will allow while loop to break

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

if lives >= 1 and guessnumber == 0:  
0 голосов
/ 13 декабря 2018

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

...