"猝死"函数在实际执行任何操作之前不止一次循环

时间:2015-03-17 22:23:45

标签: python function loops while-loop

我的代码中的函数和循环有点麻烦。基本上问题是"突然死亡"功能应该只运行一次并完成游戏。然而,它循环约3-5次然后完成游戏。

以下是完整代码的pastebin链接:http://pastebin.com/zTv35W8N

但是,这是导致问题的功能:

def suddendeath():
    global charone_strength
    global chartwo_strength
    print "\n============"
    print "SUDDEN DEATH"
    print "============"
    time.sleep(1)
    player1 = random.randint(1,6)
    player2 = random.randint(1,6)
    print "\n"+str(charone)+" has rolled:",player1
    time.sleep(0.5)
    print "\n"+str(chartwo)+" has rolled:",player2
    if player1 == player2:
        print "\nIt's a draw!"
        suddendeath()
    if player1 > player2:
        chartwo_strength = 0
    elif player2 > player1:
        charone_strength = 0

这是循环:

while charone_strength > 0 or chartwo_strength > 0:
    if counter == 220:
        print "\nRound 220 has been reached, Sudden Death Mode active!"
        suddendeath()
    else:
        mods()
        battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, strength_mod, skill_mod)
else:
    if charone_strength <= 0:
        print "\n"+str(charone)+" has died!",chartwo,"wins!"
        time.sleep(1)
    elif chartwo_strength <= 0:
        print "\n"+str(chartwo)+" has died!",charone,"wins!"
        time.sleep(1)
    play = raw_input("Would you like to play again? y/n: ")
    if play in ["yes","y","Yes","Y"]:
        execfile("gcse.py")
    else:
        print "Goodbye! Thanks for playing!"
        exit()

我建议先阅读完整的代码,但在解决此问题时,我们将不胜感激任何见解和进一步的帮助。干杯:)

1 个答案:

答案 0 :(得分:0)

如果suddendeath应该完成游戏,你应该在执行后退出循环,例如:

...
if counter == 220:
    print "\nRound 220 has been reached, Sudden Death Mode active!"
    suddendeath()
    break

现在问题是else循环的while部分如果break发生则不会被执行。据我所知,这个代码应该在任何情况下执行,所以只需在while之后写一个else

P.S。还有其他问题,例如counter未在任何地方定义或更新,但我想这是因为您没有发布完整的工作代码。

修改:忽略这个答案,只留下历史记录。真正的问题似乎是在条件

while charone_strength > 0 or chartwo_strength > 0:

应该是

while charone_strength > 0 and chartwo_strength > 0:

如果一个的玩家达到力量0而不是两个,游戏就会结束。