python-只要按下键,如何使游戏对象连续移动?

提问

我试图使游戏对象(在此为欢迎文本)移动,只要按下键盘上的键即可.但是在我的这段代码中

import pygame , sys
from pygame.locals import *

pygame.init()

WHITE = (255 , 255 , 255)
RED   = (255 , 0 , 0)

DISPLAYSURF = pygame.display.set_mode((800 , 400))
pygame.display.set_caption('Welcome Tanks')

#render(text, antialias, color, background=None)
fontObj = pygame.font.SysFont('serif' , 40)
text = fontObj.render('Welcome Folks' , True , RED )

x = 150
y = 29

while True:
    DISPLAYSURF.fill(WHITE)
    DISPLAYSURF.blit(text ,(x , y))   
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
        elif event.type == KEYDOWN or event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit(0)
            elif event.key == K_DOWN:               
                y += 15
            elif event.key == K_UP:
                y -= 15
            elif event.key == K_RIGHT:
                x += 14
            elif event.key == K_LEFT:
                x -= 15
            else:
                x = 150
                y = 29
    pygame.display.update()

即使长时间按下该键,对象也只能移动一次.换句话说,当按下键盘按钮时,对象仅改变其位置一次.我希望它在按住键的同时连续移动.

我应该寻找哪个事件而不是event.KEYDOWN?

最佳答案

我建议您使用key.get_pressed(),例如

while True:
    DISPLAYSURF.fill(WHITE)
    DISPLAYSURF.blit(text ,(x , y))   
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
        elif event.type == KEYDOWN or event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit(0)

    if  pygame.key.get_pressed()[K_LEFT]:
        x -= 15

    if  pygame.key.get_pressed()[K_RIGHT]:
        x += 14

    if  pygame.key.get_pressed()[K_UP]:
        y -= 15

    if  pygame.key.get_pressed()[K_DOWN]:
        y += 15
    pygame.display.update()

pygame.key.get_pressed()

Returns a sequence of boolean values representing the state of every
key on the keyboard. Use the key constant values to index the array. A
True value means the that button is pressed.

Getting the list of pushed buttons with this function is not the
proper way to handle text entry from the user. You have no way to know
the order of keys pressed, and rapidly pushed keys can be completely
unnoticed between two calls to pygame.key.get_pressed(). There is also
no way to translate these pushed keys into a fully translated
character value. See the pygame.KEYDOWN events on the event queue for
this functionality.

你也可以看一下doc