pygame级别一次一个地组织和运行功能

时间:2015-06-08 17:38:06

标签: python pygame

我做了一个游戏,但我有两个屏幕要显示,菜单页面和游戏页面。在菜单页面上,当我点击播放按钮时,它显示游戏没有任何问题但是当我关闭正在运行的游戏时,它会返回到菜单屏幕,但我希望两个屏幕都退出。

请非常感谢任何帮助。

示例代码:

菜单屏幕

def menu():
    running = True

    while running:
        screen.blit(intros, (0,0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        GUI.button("Play game", 24,300, 128,50, violet, blue, screen, MAIN)
        necessary things here!

def MAIN():
    running = True

    while running:
        screen.blit(intros, (0,0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        all action starts here

请有人可以给我一个关于如何运行菜单游戏的建议,以便当点击播放按钮并且MAIN代码正在运行时,当我点击关闭时,游戏停止并且不会返回到菜单代码。

我已经在几个论坛上阅读过使用if __name__ = "__main__",但我觉得它没用,也许我不知道如何正确实现它

3 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为你有两个while循环。设置running = False只会退出当前的循环播放,因此您只需将MAIN保留为最后一位,然后返回menu

如果要设置running = False退出两个循环,请将其设为全局变量(并且只包含其中一个)。

running = True
def menu():
    ...
def MAIN():
    ...

如果您想完全退出该计划,也可以使用import syssys.exit()。但我推荐第一个。

答案 1 :(得分:1)

现在是分割代码的好时机。我建议你只有一个循环。查看State模式。

您需要的是一个可以在适当的时刻调用屏幕中的功能的单个类。我会在这里草拟一个你可以继续的草稿。

class Window:
    def __init__(self):
        self.state = Menu()
        self.screen = initPygame()
    def run():
        self.state.draw(self.screen)
        self.state.update()
        for event in pygame.event.get():
            self.state.handleEvent(event) 
            if event.type == pygame.QUIT:
                running = False

class Menu:
    def __init__(self):
        pass
        #initialize all menu things (images etc)
    def handleEvent(self, event):
        #change state caused by event
        pass
    def draw(self, screen):
        pass
    def update(self):
        #called once per frame
        pass

答案 2 :(得分:1)

在代码中没有太大变化的简单解决方案是,只需使用peek查找QUIT事件而不将其从事件队列中删除:

def MAIN():
    while True:
        screen.blit(intros, (0,0))
        if pygame.event.peek(pygame.QUIT):
            # since we're in a function, we can simply use return
            return
        for event in pygame.event.get():
            # handle other events

        #all action starts here

另一种方法是使用pygame.event.post再次发布QUIT事件:

def MAIN():
    while True:
        screen.blit(intros, (0,0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.event.post(pygame.QUIT)
                # since we're in a function, we can simply use return
                return 

        #all action starts here

但这有点难看,虽然它确保事件冒泡到menu循环。

最好的解决方案恕我直言,要求你重写大部分代码,就是使用一个主循环和一个状态来决定你现在正在处理的场景(菜单或游戏玩法)

看一下这些问题/答案的灵感: