我正在研究一个程序,我需要切换不同的循环。 当我尝试切换回上一个循环时,这种情况会让我感到崩溃。
有什么建议吗?
P.S。下面是例子
e.g。功能=主页
(改变循环)
功能= 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()
答案 0 :(得分:1)
它没有崩溃。它只是在最后一个循环中将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()
答案 1 :(得分:0)
你的轨道很好。
试试这个:
示例代码:
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()
,保留一个状态列表,以便您可以将新状态置于顶部,然后弹出它并返回到之前处于的状态。这样可以轻松管理多个游戏屏幕。