I have two while-loops in my program. The first one is for the game-menu and the second one is for the actual game. If the "gameover-event" occurs I want to go back to the Menu. I don´t exactly know how to do this.
# 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()
One way to do this is to use functions instead of nested while loops:
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
Setting running = 1 would also work, but using functions keeps things cleaner and more organized.
How you can do this, Here it is:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.