从一个while循环跳回到另一个while循环

时间:2021-03-19 15:16:24

标签: python loops

我的程序中有两个 while 循环。第一个用于游戏菜单,第二个用于实际游戏。如果发生“游戏结束事件”,我想返回菜单。我不知道该怎么做。

 # Keep window running (Infinite-Loop)
    running = 1
    
    # Menu-loop
    while running == 1:

        # Start game
        if event.key == pygame.K_SPACE:
             running = 2
    
        # Game While-Loop (Everything that takes place during the game is inside here)
        while running == 2:
    
            # Show gameover-messages when event occurs
            if gameover:
                obstacle_list.clear()
                speed_up = 0
                speed_down = 0
                show_gameover(go_textX, go_textY)
                show_gameover_message()

2 个答案:

答案 0 :(得分:2)

一种方法是使用函数而不是嵌套的 while 循环:

def game_loop():
    # do stuff

    while True:
        if gameover:
            # do other stuff

            return # returns back to main_loop

def main_loop():
    running = 1

    while running == 1:
        if event.key == pygame.K_SPACE:
            game_loop()

main_loop() # simply call the main_loop function to start window

设置 running = 1 也可以,但使用函数可以使事情更清晰、更有条理。

答案 1 :(得分:2)

如何做到这一点,这是:

running=1
while running == 1:
    # Do stuff as you want
   
    if event.key == pygame.K_SPACE:
         running = 2

    while running==2:
        # Do stuff for running the Game
        if event.key == 'exit': # Here you can take input any key for exit the game
            running = 1