In Pygame, the image doesn't get erased when moved to another location on the game window

Viewed 38

I have been trying out the Pygame game library on my Mac, and when I got to try moving around an image around the game window, for some reason, it doesn't get erased.

The code I tried to run:

import pygame

pygame.init()

# Creates the screen.
screen = pygame.display.set_mode([800, 600])
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load("ufo.png")
pygame.display.set_icon(icon)

# Player sprite.
playerImg = pygame.image.load("player.png")
playerX = 350
playerY = 500
playerX_change = 0

# Function to draw the player
def player(x, y):
  screen.blit(playerImg, (playerX, playerY))

# Game loop
running = True
while running:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            playerX_change = -0.1
            print("Left key is pressed!")
        if event.key == pygame.K_RIGHT:
            playerX_change = 0.1
            print("Right key is pressed!")

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
            playerX_change = 0

playerX += playerX_change

I have tried to run similar code on my PC, and it worked like intended. I have no idea what to do.

1 Answers

You have to clear the screen in every frame:

clock = pygame.time.Clock()

running = True
while running:
    clock.tick(100)

    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    # update objects
    speed = 1
    keys = pygame.key.get_pressed()
    playerX += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed

    # clear screen
    screen.fill(0)

    # draw scene
    player(playerX, playerY)

    # update display
    pygame.dispaly.flip()

The typical PyGame application loop has to:

Related