我做了一些添加和修改以使您的代码正常工作。在每一帧(循环的迭代)中,您必须擦除屏幕并重新绘制桨。这是为了确保在按下 LEFT/RIGHT 箭头时使用新坐标重新绘制桨叶。请注意,当按下 LEFT 时,我更改了 p1Paddle.left 而不是 p1Paddle.right。
import pygame, sys
from pygame import *
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Paddle Movement')
PADDLE_WIDTH = 50
PADDLE_HEIGHT = 10
paddleSpeedX = 0
p1Paddle = pygame.Rect(10, 430, PADDLE_WIDTH, PADDLE_HEIGHT)
PADDLE_COLOR = pygame.color.Color("red")
while True:
# clear screen with black color
screen.fill( (0,0,0) )
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_LEFT:
p1Paddle.left = p1Paddle.left + paddleSpeedX - 10
if event.key == K_RIGHT:
p1Paddle.left = p1Paddle.left + paddleSpeedX + 10
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
# draw the paddle
screen.fill( PADDLE_COLOR, p1Paddle );
pygame.display.update()
一个更优雅的解决方案是下面的
import pygame, sys
from pygame import *
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Paddle Movement')
PADDLE_WIDTH = 50
PADDLE_HEIGHT = 10
paddleSpeedX = 0
p1Paddle = pygame.Rect(10, 430, PADDLE_WIDTH, PADDLE_HEIGHT)
PADDLE_COLOR = pygame.color.Color("red")
# clock object that will be used to make the game
# have the same speed on all machines regardless
# of the actual machine speed.
clock = pygame.time.Clock()
while True:
# limit the demo to 50 frames per second
clock.tick( 50 );
# clear screen with black color
screen.fill( (0,0,0) )
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
p1Paddle.left = p1Paddle.left + paddleSpeedX - 5
if keys[K_RIGHT]:
p1Paddle.left = p1Paddle.left + paddleSpeedX + 5
# draw the paddle
screen.fill( PADDLE_COLOR, p1Paddle );
pygame.display.update()
请注意,我使用 . 检查按键pygame.key.get_pressed()
。当我们检查键状态并且不等待事件发生时,它允许进行平滑的移动。我添加了一个时钟对象以将帧速率限制为 50 FPS(每秒帧数)。
请尝试这两种方法。