Python 中嵌套 While 循环的事件顺序是什么?

What's the order of events for nested While loops in Python?

我正在自学 Python,我正在尝试使用我熟悉的 RPG 机制制作一款基本游戏。我的核心机制是这样的:

while not GameOver():                    #checking for one side or the other to be all KO'd
    turnbegin()                          #resetting # of moves per player, etc
    while not TurnDone():                #checking to see if everyone's out of moves
        for ch in activechars:           #going through the players who still have moves
            if ch not in defeatedchars:  #ignoring the KO'd players
                attack(ch,target(ch))    #EVERYONE PUNCH EVERYONE (keeping it simple)
            else:
                pass

我的问题是这个循环在它应该命中 GameOver() 之后仍在尝试 运行 target(ch) 函数。计数器已关闭(每个人都被 KO'd)并且 GameOver 功能似乎正常工作;我检查了。但是 GameOver returns True 然后......它只是滚动到 attack() 并踢回一个错误,它没有任何人可以瞄准而不是因为结束而停止。我尝试创建一个 gameover=GameOver() 变量并改为说“虽然不是游戏结束”,但它在说第 2 回合开始后就卡在了 turnbegin() 中。

感谢您阅读本文!我对此很陌生,非常感谢您的帮助。

“while not GameOver()”仅在完成 ​​运行 并需要进入另一个循环时才被评估。

由于 TurnDone() 仍然为真,它不会退出循环并且 GameOver() 不是 re-evaluated。

当 GameOver() 更新为 True 时,TurnDone() 也应该变为 True 以防止它进入另一个循环。

您是否尝试在 attack() 之后更新 activechars 列表? 此外,如果在 for 循环内的 attack() 之后没有逻辑,您可以替换

else:
    pass

什么都没有,就去骑吧,其他的都是无关紧要的。保持代码整洁。

你应该使用 pep-8(activechars 必须是 active_chars,等等)

假设您将 activechars 和 defeatedchars 存储在列表中,也许您可​​以这样做:

# This boolean will be False if there are no more undefeated active chars.
have_active_undefeated_chars = True

while not GameOver() and have_active_undefeated_chars:
    turnbegin()
    while not TurnDone():

        activechars_not_defeated = list(set(activechars) - set(defeatedchars))
        if len(activechars_not_defeated) == 0:
            have_active_undefeated_chars = False
            break

        for ch in activechars_not_defeated:
            attack(ch,target(ch))

activechars_not_defeated 获取 activechars 中不在 defeatedchars 中的元素,boolean have_active_undefeated_chars 告诉你是否还有未被击败的 active chars。 break 语句将使您脱离两个 while 循环,而 have_active_undefeated_chars 确保循环不会再次 运行。

您还可以将 activechars_not_defeated 列表用于 for 循环。

当然,我不熟悉你的整个代码,所以我不知道这是否适用于上下文。但希望这会有所帮助。