0

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()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Avyay Nair
  • 23
  • 4

2 Answers2

0

"running" is not associated with anything. You need a while running loop.

running = True
while running:

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

        screen.fill((120,120,120))
        pygame.display.update()

However this will not exit as you have:

while True:
    a.state_manager()

Which is always true. remove the while true from around it and it should exit

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
marienbad
  • 1,461
  • 1
  • 9
  • 19
  • Hi! I tried that it somehow still won't exit. – Avyay Nair May 30 '21 at 05:07
  • pygame,QUIT events are only generated when the x that closes the window is clicked, not on a keypress. – marienbad May 30 '21 at 05:18
  • @marienbad Your answer is wrong. Adding the code in your answer creates multiple event loops. See [Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?](https://stackoverflow.com/questions/58086113/faster-version-of-pygame-event-get-why-are-events-being-missed-and-why-are/58087070#58087070) – Rabbid76 May 30 '21 at 06:40
  • Lol I should have specified that this goes in the intro() function but thought that was obvious from the context. I shouldn't SO just before bed lol. – marienbad May 30 '21 at 13:48
  • @marienbad Knowing that your answer is wrong, please consider correcting or deleting the answer. – Rabbid76 Sep 12 '21 at 17:28
0

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()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174