Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pygame movement causes the object to duplicate

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ä

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading