首页 > 解决方案 > While 循环在需要时不起作用

问题描述

我这里的战斗代码在执行一次时只会坐下来,不会崩溃也不会做任何事情。我想要它做的是循环并让战斗继续直到野兽死去(我稍后会添加玩家)

我是 Python 新手,但仍然不太了解它,这意味着我看不出我的代码有什么问题。

最初,我切换if damage==0到 elif,但代码仍然会无限期地坐着,什么也不做。它也不会破裂。

任何帮助,将不胜感激。

a=1
z=int(30*a**2)
y=random.randint(0,0)
x=0
if y == 0:
    print("A wild Ragnabeast appeared!")
    z=int(30*a**2)
    b=int(30)
    c=random.randint(0,5)
    fight= True
    while fight == True: # Here is where the loop is supposed to start. The issue is that it starts once, and never again.
        user_input=input("What will player do? You can run or attack.")
        if user_input=="run":
            break
        elif user_input=="attack":
            print("The player punched the Ragnabeast!")
            d=int(random.randint(0,5))
            b = b - d
            if d==0:
                    print("The player missed.")
                    x+=1
            elif d!=0:
                    print("The player dealt",d,"d.")
                    print("The Ragnabeast has",b,"HP left.")
                    x+=1
            if a=="1":
                    d=random.randint(0,5)
                    d=int(random.randint(0,5))
            if d==0:
                    print("The Ragnabeast rammed into the player!")
                    print("The player took",d,"damage.")
                    z-=d
            if d==1:
                    print("The Ragnabeast bit the player!")
                    print("The player took",d,"damage.")
                    z-=d
            if d==2:
                    print("The Ragnabeast hit the player with its tail!")
                    print("The player took",d,"damage.")
                    z-=d
            if d==3:
                    print("The Ragnabeast spewed flames into the player!")
                    print("The player took",d,"damage.")
                    z-=d
            if d==4:
                    print("The Ragnabeast launched a rock at the player!")
                    print("The player took",d,"damage.")
                    z-=d
            if d==5:
                    print("The Ragnabeast's piercing stare shocked the player!")
                    print("The player took",d,"damage.")
                    z-=d
            if z <= 25:
                    print("The Ragnabeast leaks propane. It roars in pain.")
            if z <=10:
                    print("The Ragnabeast's flames start to die out. It will die soon.")
            while z != 0:
                    fight = True
            else:
                    print("The Ragnabeast has died.")
                    fight = False

                                ```

标签: python-3.x

解决方案


如果该True值不起作用,您应该能够使用字符串来代替它。

前任:

fight = True变成fight = "true"

fight = False变成fight = "false"

while fight == True:变成while fight == "true":

这是一个非常适合贫民区的解决方法,但它应该有效。

另外,我注意到一些变量的名称只是字母。不想唠叨,但这在编码社区被认为是一个坏习惯。尝试给他们更多描述性的名称。

我希望我有所帮助!


推荐阅读