[英]How to switch between multiple while statements in Python
我正在開發一個程序,我需要切換不同的循環。 當我嘗試切換回上一個循環時,這會導致崩潰。
有什么建議么?
PS下面是例子
例如Function = Home
(更改循環)
功能= txtbox
(更改循環)
功能=主頁(此處崩潰)
import pygame, sys, time, random
from pygame.locals import *
import math
import sys
import os
# set up pygame
pygame.init()
# set up the window
WINDOWWIDTH = 1200
WINDOWHEIGHT = 650
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 1, 32)
pygame.display.set_caption("Mango")
Function = "Home"
font = pygame.font.SysFont("Fonts", 30)
#colors
TEXTCOLOR = (255, 255, 255)
TEXTCOLORS = (255, 0, 0)
# run the game loop
while Function == "Home":
# check for the QUIT event
events = pygame.event.get()
for event in events:
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP:
Function = "txtbox"
break
pygame.display.flip()
while Function == "txtbox":
events = pygame.event.get()
# process other events
for event in events:
if event.type == pygame.MOUSEBUTTONUP:
Function = "Home"
break
pygame.display.flip()
它不會崩潰。 當在最后一個循環中將Function
設置為“ Home”時,它僅完成執行。 該循環只是結束。
嘗試將這兩個while循環封裝在永遠運行的while循環中。
while True:
while Function == "Home":
# check for the QUIT event
events = pygame.event.get()
for event in events:
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP:
Function = "txtbox"
break
pygame.display.flip()
while Function == "txtbox":
events = pygame.event.get()
# process other events
for event in events:
if event.type == pygame.MOUSEBUTTONUP:
Function = "Home"
break
pygame.display.flip()
您進展順利。
嘗試這個:
示例代碼:
def home():
events = pygame.event.get()
for event in events:
...
if something_happened:
switch_state(txtbox)
def txtbox():
events = pygame.event.get()
for event in events:
...
if something:
switch_state(home)
Function = home # assign the function itself to a variable
def switch_state(new_state):
global Function
Function = new_state
...
while True:
Function() # call the function which is currently active
下一步:
Function()
,以便您可以在頂部推一個新狀態,然后將其彈出並返回到以前處於的任何狀態。 這將使您輕松管理多個游戲屏幕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.