Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

python - pygame.key.get_pressed() is not working

I've read similar questions to this on Stack Overflow but they have not helped. Here is my code:

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Hello World')
pygame.mouse.set_visible(1)

done = False
clock = pygame.time.Clock()

while not done:
    clock.tick(60)

    keyState = pygame.key.get_pressed()

    if keyState[pygame.K_ESCAPE]:
        print('
Game Shuting Down!')
        done = True

Pressing escape does not exit the game or print a message. Is this a bug? If I print the value for keyState[pygame.K_ESCAPE], it is always zero.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that you don't process pygame's event queue. You should simple call pygame.event.pump() at the end of your loop and then your code works fine:

...
while not done:
    clock.tick(60)

    keyState = pygame.key.get_pressed()

    if keyState[pygame.K_ESCAPE]:
        print('
Game Shuting Down!')
        done = True
    pygame.event.pump() # process event queue

From the docs (emphasis mine):

pygame.event.pump()

internally process pygame event handlers

pump() -> None

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.

Note that you don't have to do this if you just call pygame.event.get() anywhere in your main-loop; if you do not, you should probably call pygame.event.clear() so the event queue will not fill up.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...