Pygame movement causes the object to duplicate

Question:

So i programmed a block which should move in pygame

But when i press any of the movement buttons it doesnt move the block it just duplicates it and moves it and the old square doesnt do anything

Yeah im probably really retarded and the answer is really obviousä

here is the script:

import pygame
from sys import exit


pygame.init()

width=800
height=800
screen = pygame.display.set_mode((width,height))
posy=500
posx=500
clock = pygame.time.Clock()

pygame.display.set_caption("Block")



while True:
    for event in pygame.event.get():
        pygame.draw.rect(screen, "red", pygame.Rect(posy, posx, 60, 60))
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
            
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                posx=posx-10
            elif event.key == pygame.K_s:
                posx=posx+10
            elif event.key == pygame.K_a:
                posy=posy-10
            elif event.key == pygame.K_d:
                posy=posy+10
            if event.key == pygame.K_ESCAPE:
                pygame.event.post(pygame.event.Event(exit()))
        


        
        pygame.display.update()
        clock.tick(60)
Asked By: Zero

||

Answers:

It looks like you’re creating a new object every time, so you need to adjust your code like this:

    rect = pygame.Rect(posy, posx, 60, 60)
    for event in pygame.event.get():
        pygame.draw.rect(screen, "red", rect)
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
            
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                rect.move_ip(0, -10)
            elif event.key == pygame.K_s:
                rect.move_ip(0, 10)
            elif event.key == pygame.K_a:
                rect.move_ip(-10, 0)
            elif event.key == pygame.K_d:
                rect.move_ip(10, 0)
Answered By: svfat
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.