【问题标题】:looping code: infinite how to stop this循环代码:无限如何停止
【发布时间】:2014-11-09 22:51:10
【问题描述】:

您好,我正在尝试创建一个循环,以便当有人在我的代码中死亡时它会停止,同样,代码不会在有人死亡之前结束(也就是说,力量或技能达到零)但是,无论数字是多少我输入,游戏总是无限继续。

我该如何解决这个问题?

while True:
    try:
        strengthA=abs(int(input("enter strength A ")))
        break          
    except ValueError:
        print("Error")
        print ("value entered")
while True:
    try:

        strengthB=abs(int(input("enter strength B ")))
        break
    except ValueError:
        print("Error")
        print ("value entered successfully")

while True:
    try:
        skillA=abs(int(input("enter skillA ")))
        break
    except ValueError:
        print("Error")
        print ("value entered successfully ")

while True:
    try:
        skillB=abs(int(input("enter skill B ")))
        break
    except ValueError:
        print("Error")
        print ("value entered successfully")



strengthmod=abs(int((strengthA-strengthB)/5))
print (strengthmod)
skillmod=abs(int((skillA-skillB)/5))
print(skillmod)


while strengthA>0 and strengthB>0:
    print strengthA, strengthB
    import random
    throwA=int(random.randrange(6)+1)
    print("Cloudy throws "+str(throwA))
    throwB=int(random.randrange(6)+1)
    print("Mocha throws "+str(throwB))

    if throwA>throwB:

        print("Cloudy wins!")
        skillA=skillA+skillmod
        strengthA=strengthA+strengthmod
        skillB=skillB-skillmod
        strengthB=strengthB-strengthmod
    elif throwA<throwB:
        print("Mocha wins!")
        skillA=skillA-skillmod
        strengthA=strengthA-strengthmod
        skillB=skillB+skillmod
        strengthB=strengthB+strengthmod
    else:
        print ("No one wins")


    if skillA<1:
        skillA=0
    if skillB<1:
        skillB=0
    print("Cloudy new skill " +str(skillA))
    print("Mocha new skill " +str(skillB))
    print("Cloudy new strength " +str(strengthA))
    print("Mocha new strength " +str(strengthB))
    if strengthA<1:
        print ("Cloudy dies")
    if strengthB<1:
        print ("Mocha dies")
    print ("Battle ends")

【问题讨论】:

  • 没有缩进就无法阅读正在发生的事情。您能否修复它,或将您的代码上传到gist.github.com
  • 实现这一点的最简单方法是设置一个变量,该变量会在危急情况下发生变化(有人死亡)。然后替换上面的while循环来检查这个变量的状态。

标签: python loops infinite


【解决方案1】:

如果strengthAstrengthB 彼此靠近,则strengthmod 将是0

strengthmod=abs(int((strengthA-strengthB)/5))

所以strengthAstrengthB 永远不会改变:

...
strengthB=strengthB-strengthmod
...
strengthA=strengthA-strengthmod
...

所以while 循环

while strengthA>0 and strengthB>0:

永远运行。

也许你应该确保strengthAstrengthB 会改变,即使strengthmod0,例如:

strengthB=strengthB-max(strengthmod, 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    相关资源
    最近更新 更多