'Pygame not exiting even after receiving keypress [duplicate]
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 1:[1]
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()
Solution 2:[2]
"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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rabbid76 |
Solution 2 | Rabbid76 |