如何在Python中的多个while语句之间切换

2024-03-28 17:56:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个程序,我需要切换不同的循环。 当我试图切换回上一个循环时,我崩溃了。在

有什么建议吗?在

注:以下是示例

例如功能=主页

(改变回路)

函数=txtbox

(改变回路)

Function=Home(此处崩溃)

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()

Tags: theimporteventhomefortypedisplaysys
2条回答

它不会崩溃。当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()不同的是,保留一个状态列表,这样你就可以把一个新的状态推到最上面,然后弹出它并返回到以前的任何状态。这将使您可以轻松地管理多个游戏屏幕。在

相关问题 更多 >