How do I fix movement in my pygame script?

Viewed 55

I am trying to make a replica for pong in pygame for my first project but when I try to move my paddles they stretch instead. I believe the reason is it creates a new rect every time I try to move it but I can't seem to figure out why. Please review the code and help rectify my mistake. Here is my code:

import pygame

W, H = 600, 500
screen = pygame.display.set_mode((W, H))
FPS = 30
class Paddle(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        super(Paddle, self).__init__()

        self.x = x
        self.y = y
        self.width = width
        self.height = height

        self.surf = pygame.Surface((width, height))
        self.surf.fill((255, 255, 255))
        self.rect = self.surf.get_rect()
        self.rect.center = (x, y)

    def move(self, distance):
        self.rect.move_ip(0, distance)

paddleA = Paddle(15, 250, 10, 50)
paddleB = Paddle(585, 250, 10, 50)

allSprites = pygame.sprite.Group()
allSprites.add(paddleA)
allSprites.add(paddleB)
run = True
clock = pygame.time.Clock()
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                run = False
    pressedKeys = pygame.key.get_pressed()

    if pressedKeys[pygame.K_UP]:
        paddleB.move(-5)
    elif pressedKeys[pygame.K_DOWN]:
        paddleB.move(5)
    elif pressedKeys[pygame.K_w]:
        paddleA.move(-5)
    elif pressedKeys[pygame.K_s]:
        paddleA.move(5)

    for sprite in allSprites:
        screen.blit(sprite.surf, sprite.rect)
    pygame.display.update()
    clock.tick(FPS)
pygame.quit()
quit()
1 Answers

Before drawing the new rect you should fill the screen with the background color, to remove the old rect. Otherwise the old one is still drawn there and you are just drawing new over the old one. Its' like painting a new picture on an old one.

screen.fill(color, rect) should do the trick.

Related