如何创建函数 'Quit'?

How to create function 'Quit'?

我了解到,如果您按下按钮 'Cross',您将无法使用 pygame.quit(),否则程序将无法运行。那么如何通过按下按钮 Sure、`QUIT' 来创建 'Quit'?

def beginning():
    Beginning = True
    while Beginning:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                Beginning = False
        #[...]
        print_text_5('Welcome to my game!', 300, 50)
        mini_button.draw(570, 200, 'PLAY', game)
        mini_button.draw(570, 420, 'QUIT', #[???])
        pygame.display.update()

def game(): 
    Game = True
    while Game:
        clock.tick(FPS)
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT:
                beginning = False
            #[...]


        if health <= 0:
            game_over()
                
def game_over():
    Game_over = True
    while Game_over:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = False

        print_text_3('Do not worry! Better luck next time!', 360, 400)
        button.draw(600, 500, 'Sure!', #[???])
        pygame.display.update()

beginning()
pygame.quit()

这是你想要的吗?

import pygame
from sys import exit as sys_exit


def quit_game():
    pygame.quit()
    sys_exit()

使用 class 变量 quit 和静态方法 set_quit 创建一个 class:

class QuitState:
    quit = False
    def set_quit():
        QuitState.quit = True

将 class 方法传递给按钮。设置 QuitState.quit 时进入应用程序循环:

def beginning():
    Beginning = True
    while Beginning and not QuitState.quit:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                QuitState.set_quit() 
        #[...]
        print_text_5('Welcome to my game!', 300, 50)
        mini_button.draw(570, 200, 'PLAY', game)
        mini_button.draw(570, 420, 'QUIT', QuitState.set_quit)
        pygame.display.update()
def game(): 
    while not QuitState.quit:
        clock.tick(FPS)
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT:
                QuitState.set_quit() 
           #[...]

        if health <= 0:
            game_over()
def game_over():
    while QuitState.quit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                QuitState.set_quit()

        print_text_3('Do not worry! Better luck next time!', 360, 400)
        button.draw(600, 500, 'Sure!', QuitState.set_quit)
        pygame.display.update()