Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does pygame freeze for me? [duplicate]

Tags:

python

pygame

Here is my code

import pygame
import sys
pygame.init()
from pygame import *
from sys import *

pygame.display.set_mode((500, 500))
pygame.time.Clock()

runGame = True

while runGame == True:

    currentKeys = pygame.key.get_pressed()

    if currentKeys[K_ESCAPE] == True:
        runGame = False

    pygame.time.Clock().tick(60)

pygame.quit()
sys.quit()

I just wanted a display that closed on Esc key press. What's wrong with this code?

like image 641
Kaiser Samsam Avatar asked Jun 20 '18 09:06

Kaiser Samsam


People also ask

What does pygame quit do?

quit() . pygame. quit() is a function that closes pygame (python still running) While pygame.

Why does pygame initialize?

You can always initialize individual modules manually, but pygame. init() initialize all imported pygame modules is a convenient way to get everything started. The init() functions for individual modules will raise exceptions when they fail.

Why is my pygame so slow?

The code runs slow because it is a heap of unstructured code (this is the cleaned up version) that is constantly loading external resources, reading events and mouse data. Structure your code so that slow things like reading from files happen ONCE. Likewise reading keys, events, etc. not once for each block.


1 Answers

Probably the event queue fills up and so the window won't react to events from your operating system/window manager.

Make sure to call pygame.event.get() (or pygame.event.pump) in your game loop.

From pygame.event.pump:

For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system. If you are not using other event functions in your game, you should call pygame.event.pump() to allow pygame to handle internal actions.

This function is not necessary if your program is consistently processing events on the queue through the other pygame.event functions.

There are important things that must be dealt with internally in the event queue. The main window may need to be repainted or respond to the system. If you fail to make a call to the event queue for too long, the system may decide your program has locked up.

like image 119
sloth Avatar answered Nov 14 '22 23:11

sloth