How to move an image smoothly in pygame

Question:

I have searched other related questions on stack overflow but can’t find the right solution.

Code Overview

basically I am trying to make a space invader game here at the bottom there is a space ship shooting down enemies and the enemies constantly move making the game hard and fun. while I am trying to make the enemies move, they paint lines which doesn’t look good.

Code

# importing modules
import pygame
import random

# initialize pygame
pygame.init()

# creating a window
screen = pygame.display.set_mode((800, 600))
# Title and Icon
pygame.display.set_caption("Space Shooters")
icon = pygame.image.load('spaceship.png')
pygame.display.set_icon(icon)

# Player
player = pygame.image.load('spaceship2.png')
playerX = 370
playerY = 500
playerX_change = 0

# Enemy
enemyImg = pygame.image.load('enemy.png')
enemyX = random.randint(6, 730)
enemyY = random.randint(45, 150)
enemyX_change = 0.3
enemyY_change = 0


# Defining and drawing spaceship
def spaceship(x, y):
    screen.blit(player, (x, y))


# Defining and drawing enemy
def enemy(x, y):
    screen.blit(enemyImg, (x, y))


# making the game window run endlessly and game loop
running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # Keystroke check (right, left)
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                playerX_change = -0.25
            if event.key == pygame.K_RIGHT:
                playerX_change = 0.25
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerX_change = 0

    # Changing X coordinates to move spaceship
    playerX += playerX_change

    if playerX <= 6:
        playerX = 6

    if playerX >= 730:
        playerX = 730

    enemyX += enemyX_change

    if enemyX <= 6:
        enemyX = 6
        enemyX_change = 0.3

    if enemyX >= 730:
        enemyX = 730
        enemyX_change = -0.3

    spaceship(playerX, playerY)

    enemy(enemyX, enemyY)
    # updating display
    pygame.display.update()

Expected Results vs Received Results

Expected Results: The enemy moves on the x axis at a constant speed and bounces back when a boundary has been hit. No trail should be formed.

Received Results: The enemy is moving as expected ,but painting a trail where it is and was going.

Asked By: Dev

||

Answers:

The display is redrawn in every frame, therefore the display must be cleared before drawing the objects in the scene:

while running:
    # [...]

    # clear the display 
    screen.fill(0)                 # <-- clear display

    # draw the scene
    spaceship(playerX, playerY)
    enemy(enemyX, enemyY)
    
    # update the display
    pygame.display.update()

The typical PyGame application loop has to:

Answered By: Rabbid76