Python Pygame无法识别键盘事件



我想制作一个程序,通过键盘移动矩形,但它不会移动,就像它不理解事件命令一样。我找不到哪里出了问题。我认为问题在于命令的顺序,但作为一个初学者,我找不到它。有人能帮我吗?谢谢

import pygame
import sys
from pygame.locals import *
fps = 30
fpsclock = pygame.time.Clock()
w = 640
h = 420
blue = (0, 0, 255)
white = (255, 255, 255)
x = w / 3
y = 350
boxa = 20
movex = 0

def drawwindow():
    global screen
    pygame.init()
    screen = pygame.display.set_mode((w, h))
    screen.fill(blue)

def drawbox(box):
    if box.right > (w - boxa):
        box.right = (w - boxa)
    if box.left < 0:
        box.left = 0
    pygame.draw.rect(screen, white, box)

def main():
    global x
    global movex
    drawwindow()
    box1 = pygame.Rect(x, y, boxa, boxa)
    drawbox(box1)
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                if event.key == K_RIGHT:
                    movex = +4
                if event.key == K_LEFT:
                    movex = -4
            if event.type == KEYUP:
                if event.key == K_RIGHT:
                    movex = 0
                if event.key == K_LEFT:
                    movex = 0
        x += movex
        pygame.display.update()
        fpsclock.tick(fps)
if __name__ == '__main__':
    main()

键盘事件被正确接受。这可以通过在其中一个if event.key == ...块中粘贴print语句来验证。

其中一个问题是,在最初绘制方框后,你永远不会重新绘制它。游戏循环的每一次迭代都应该重新绘制背景(理想情况下只绘制变化的区域,但这是以后的事)和新位置的方框。类似这样的东西:

while True:
    # [event handling code omitted for brevity]
    x += movex
    drawwindow()
    drawbox(box1)
    pygame.display.update()
    fpsclock.tick(fps)

然而,还有另一个问题。更改xmovex对任何事情都没有影响,因为一旦进入主循环,它们就不会在任何地方使用。如果x属性发生更改,则框将移动,而不是x += movex,如以下代码所示:

while True:
    # [event handling code omitted for brevity]
    box1.x += movex # this line changed
    drawwindow()    # this line added
    drawbox(box1)   # this line added
    pygame.display.update()
    fpsclock.tick(fps)

使用上面的更改运行您的代码,框现在移动。