The keyboard events ( pygame.KEYDOWN
, pygame.KEYUP
) occur only one time when a key is pressed, respectively released.
(键盘事件( pygame.KEYDOWN
, pygame.KEYUP
)仅在分别按下和释放一个键时发生一次。)
If x_vary = 0
and y_vary = 0
are declared in the main application loop, then they are set when a button is pressed, but they are reinitialized (0) immediately in the next frame.
(如果在主应用程序循环中声明了x_vary = 0
和y_vary = 0
,则在按下按钮时将它们置位,但它们将在下一帧立即重新初始化(0)。)
You've to presse a button again to set them. (您必须再次按下按钮进行设置。)
If x_vary = 0
and y_vary = 0
are declared before the main application loop, then they keep the value, which is set when a button is pressed.
(如果在主应用程序循环之前声明x_vary = 0
和y_vary = 0
,则它们将保留该值,该值在按下按钮时设置。)
If a button is released, then both are set 0. (如果释放按钮,则两者都设置为0。)
Use pygame.key.get_pressed()
, to evaluate if the state of a key is pressed.
(使用pygame.key.get_pressed()
评估是否按下了键的状态。)
pygame.key.get_pressed()
get the state of all keyboard buttons and a the state of a key is True
as long the keyboard is pressed down. (pygame.key.get_pressed()
获取所有键盘按钮的状态,并且只要按下键盘,键的状态为True
。)
eg: (例如:)
game_run = False
while game_run == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_run = True
keys = pygame.key.get_pressed()
x_vary, y_vary = 0, 0
if keys[pygame.K_LEFT]:
x_vary = -10
if keys[pygame.K_RIGHT]:
x_vary = +10
if keys[pygame.K_UP]:
y_vary = -10
if keys[pygame.K_DOWN]:
y_vary = +10
x += x_vary
y += y_vary
game_window.fill((128, 0, 0))
car(x, y)
pygame.display.update()
clock.tick(60)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…