1

My character, like most characters, is supposed to be repeatedly replaced by the same image a few pixels over to simulate movement. Instead, my code causes the image to be copied when I move it, and right now it's more like a drawing application than a moving character. Can someone please tell me why this is happening and what can be done to replace the previous image? Thanks in advance.

import pygame, sys
from pygame.locals import *

pygame.init()
DISPLAYSURF=pygame.display.set_mode((800,800))
pygame.display.set_caption('Hola Amigos!')

pixel_one=pygame.image.load('pixel_one.png')
pixel_one=pygame.transform.scale(pixel_one, (5,5))

def pixel(pixel_onex,pixel_oney):
        DISPLAYSURF.blit(pixel_one, (pixel_onex, pixel_oney))

pixel_onex=10
pixel_oney=10

x_change=0
y_change=0

while True: #main game loop
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN: 
            if event.key == pygame.K_LEFT:
                x_change = -5
            elif event.key == pygame.K_RIGHT:
                x_change = 5
            elif event.key == pygame.K_UP:
                y_change = -5
            elif event.key == pygame.K_DOWN:
                y_change = 5

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or pygame.K_RIGHT or pygame.K_UP or pygame.K_DOWN:
                x_change=0
                y_change=0
        if event.type==QUIT:
            pygame.quit()
            sys.exit()

    pixel_onex += x_change
    pixel_oney += y_change

    pixel(pixel_onex,pixel_oney)

    pygame.display.update()
Nathan
  • 8,093
  • 8
  • 50
  • 76
ZacGM
  • 13
  • 5
  • 2
    This happens because you're not [clearing your screen](http://stackoverflow.com/questions/21257865/how-to-clear-up-screen-in-pygame) before drawing, so the "old" image is still there. – Cubic Aug 27 '16 at 15:47

1 Answers1

1

Before you enter the main loop, add a statement like

background = pygame.Surface(DISPLAYSURF.get_size())

and then blit background onto DISPLAYSURF. At each iteration, after everything has been updated but before anything else has been drawn, blit your background onto the DISPLAYSURF to create a clean surface.

Chad Davis
  • 174
  • 3
  • It worked, thanks. For those who may have the same issue in the future, all I did in addition to the code in my problem statement was add Chad's line of code right after defining my pixel function. Then I went back into my pixel function and between defining the function name and blitting pixel_one, I added...DISPLAYSURF.blit(background,(0,0))...works perfectly. – ZacGM Aug 27 '16 at 17:34
  • @ZacGM If your background is just a single color you could do `DISPLAYSURF.fill(background_color)` where `background_color` is a tuple/list of 3 (R, G, B) or 4 (R, G, B, A) elements instead. Each element should be an integer between 0-255. – Ted Klein Bergman Aug 27 '16 at 18:24