pygame.key.get_pressed()不起作用

2024-05-15 02:49:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我读过类似的关于堆栈溢出的问题,但它们没有帮助。这是我的代码:

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('\nGame Shuting Down!')
        done = True

escape不会退出游戏或打印消息。这是虫子吗?如果我打印keyState[pygame.K_ESCAPE]的值,它总是零。


Tags: 代码fromimportinit堆栈modedisplayscreen
3条回答

我可以建议改用事件que吗?这可能是个更好的主意:

while True: #game loop
    for event in pygame.event.get(): #loop through all the current events, such as key presses. 
        if event.type == QUIT:
            die()

        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE: #it's better to have these as multiple statments in case you want to track more than one type of key press in the future. 
                pauseGame()

问题是您没有处理pygame的事件队列。您应该在循环结束时简单地调用pygame.event.pump(),然后您的代码就可以正常工作了:

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

    keyState = pygame.key.get_pressed()

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

来自docs(强调我的):

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.

请注意,如果只在主循环中的任何地方调用pygame.event.get(),则不必执行此操作;如果不调用,则可能应该调用pygame.event.clear(),这样事件队列就不会填满。

做这样的事:

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)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    key = pygame.key.get_pressed()

    if key[K_ESCAPE]:
        print('\nGame Shuting Down!')

    pygame.display.flip()

您不需要if语句上的pygame.,还应该调用pygame.display.flip(),以便它正确显示窗口,然后您需要一个事件循环来退出程序

相关问题 更多 >

    热门问题