Pygame sprite constantly redrawn to screen and not moving

Viewed 210

I can't see what's wrong with the below code. All I want to do is make the frog move across the screen, but it is simply redrawing many, many frogs all one pixel apart. How do I move the frog rather than just draw it again?

import pygame
from pygame.constants import *

pygame.init()

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))


class Frog(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()
        self.image = pygame.transform.scale(pygame.image.load('frog.png'), (64, 64))
        self.rect = self.image.get_rect()
        self.dx = 1

    def update(self, *args):
        self.rect.x += self.dx


running = True
frog = Frog()
entities = pygame.sprite.Group()
entities.add(frog)
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
    entities.update()
    entities.draw(screen)
1 Answers

That is how you do it in Pygame, you just redraw objects every iteration to give the illusion that they're moving but you must cover up the previous drawn objects by filling your window with a solid color e.g.

screen.fill((255, 255, 255))

This should be at the start of your game loop so you have a fresh canvas for drawing your objects each iteration.

while running:
    screen.fill((255,255,255))
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
    entities.update()
    entities.draw(screen)
    pygame.display.update()

You may have to use the pygame.display.update() function to update the whole screen rather than just your entities.

Related