Can anyone tell me why this png keeps creating a clone every time it hits a boundary?

Viewed 22

So Im really new to pygame and trying to recreate space invaders. This is just the code for the enemy, can anyone tell me why it keep messing up whenever it hits a boundary? Im using pycharm to code this btw.

import pygame
screen = pygame.display.set_mode((800, 600))
pygame.init()
enemyIMG = pygame.image.load("ufo (2).png")
enemyX = 360
enemyY = 50
enemyY_change = 40
enemyX_change = 0.3


def enemy(x, y):
    screen.blit(enemyIMG, (x, y))


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

    enemyX += enemyX_change
    if enemyX <= 0:
        enemyY += enemyY_change
        enemyX_change = 0.3
    elif enemyX >= 736:
        enemyY += enemyY_change
        enemyX_change = -0.3
    enemy(enemyX, enemyY)
    pygame.display.update()

I was trying to make the alien hit a boundary then go down 40 pixels, then go the other way. But instead, it created a clone of its self and stayed there while the other clone continued as normal.

1 Answers

The entire scene is redrawn in every frame. Therefor you have to clear the display in every frame:

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

    enemyX += enemyX_change
    if enemyX <= 0:
        enemyY += enemyY_change
        enemyX_change = 0.3
    elif enemyX >= 736:
        enemyY += enemyY_change
        enemyX_change = -0.3

    # clear display
    screen.fill((0, 0, 0))       # <-- this is missing

    # draw scene
    enemy(enemyX, enemyY)

    # update display
    pygame.display.update()

The typical PyGame application loop has to:

Related