1

I am trying to understand why my program is loosing respond when I trying exit from game. I make some test and here is code:

import pygame
import time

pygame.init()

run=True

pygame.display.set_caption("test")
win=pygame.display.set_mode((200,200))

while run==True:
    pygame.time.delay(16)
    keys=pygame.key.get_pressed()
    #for event in pygame.event.get():
        #if event.type == pygame.QUIT:
            #run=False

    win.fill((125,125,125))
    if keys[pygame.K_q]:
            run=False
    pygame.display.update()
pygame.quit()

If execute this code - windows can't properly exit from program when user pressed key "q". If remove comments symbols # form 14,15,16 strings, all will work properly. Hitting "q" key will exit from program normally. Only one question - why???

RedSubmarine
  • 177
  • 4
  • 16

1 Answers1

2

You have to handle the events in the application loop. See pygame.event.get() respectively 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 don't handle the events, pygame.key.get_pressed() will stop working. The states of the keys returned by pygame.key.get_pressed() are evaluated internally when the events are handled.

At least you've to call pygame.event.pump():

while run==True:
    pygame.time.delay(16)
    pygame.event.pump()

    keys=pygame.key.get_pressed()
    if keys[pygame.K_q]:
        run=False

    win.fill((125,125,125))
    pygame.display.update()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • So only one string added to code (for example) a=pygame.event.get() (even a not use in code) make all work properly. Thx for answer! – RedSubmarine Nov 28 '20 at 20:26