Moving an object left and right

dan picture dan · Jul 6, 2012 · Viewed 18.4k times · Source

I have a problem with Python and pygame: I have no idea how to make a simple paddle move left and right. Basically I am working on a pong type game for my first project.

After reading a few articles online I thought of a way of how to do this. The code I have so far is:

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:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                p1Paddle.right = 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()

    pygame.display.update()

After entering this code the game runs but I still cannot move the paddle left and right. How can I do this?

Answer

Michael0x2a picture Michael0x2a · Jul 6, 2012

Pygame raises a KEYDOWN event only once, when you first hit a key.

Unfortunately, it won't continue to raise a KEYDOWN event, so what's happening is that your paddle is jerking over only once, and won't move again unless you keep spamming the left or right key.

Instead, what you could do is set a velocity when you recieve a KEYDOWN event, and set it back to zero when you get KEYUP, like so:

while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                p1Paddle.x_velocity = -10
            elif event.key == pygame.K_RIGHT:
                p1Paddle.x_velocity = 10
        if event.type == pygame.KEYUP:
            if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
                # if either the left or right arrow keys are released
                p1Paddle.x_velocity = 0
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    p1Paddle.x_distance += p1Paddle.x_velocity
    # other stuff here
    # drawing code here
    pygame.display.update()

(I also changed some of your variable names, since I couldn't figure out what p1Paddle.left and p1Paddle.right were -- I hope you don't mind).