gpt4 book ai didi

python - pygame.key.get_pressed() 不工作

转载 作者:太空狗 更新时间:2023-10-29 21:22:30 24 4
gpt4 key购买 nike

我在 Stack Overflow 上阅读过与此类似的问题,但没有帮助。这是我的代码:

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] 的值,它始终为零。

最佳答案

问题是您不处理 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() 这样事件队列就不会填满。

关于python - pygame.key.get_pressed() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17938170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com