pythonpygamegame-loop

Pygame not exiting even after receiving keypress


So I'm trying to exit the pygame using a function but its not working. It's definitely entering the function block but for some reason is not quitting after the keypress.

import pygame
from pygame import mixer
from random import *
from math import *

pygame.init()

screen = pygame.display.set_mode((1280, 720))
pygame.display.set_caption("The Rake Game")
font = pygame.font.Font('freesansbold.ttf',32)

running = True

class Paths:
    def __init__(self):
        self.game_state = 'intro'

    def intro(self):
        screen.fill((120,120,120))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        pygame.display.update()

    def state_manager(self):
        if self.game_state == 'intro':
            self.intro()

a = Paths()

while running:
    a.state_manager()

Solution

  • running is a variable in global namespace. You have to use the global statement if you want to be interpret the variable as global variable.

    class Paths:
        # [...]
    
        def intro(self):
            global running  # <--- add global statement
    
            screen.fill((120,120,120))
    
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
    
            pygame.display.update()