I'm trying to make a square move on the screen. I planned on doing this by adding int 50 to the x-coordinate variable of my square object:
while run:
pygame.time.delay(500)
square = Square("crimson",x,200)
x+=50
However, it only elongates the square horizontally in every iteration. Below is the full code:
import pygame
pygame.init()
screen = pygame.display.set_mode((500,500))
class Square(pygame.sprite.Sprite):
def __init__(self,col,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50,50))
self.image.fill(col)
self.rect = self.image.get_rect()
self.rect.center = (x,y)
x = 200
squares = pygame.sprite.Group()
run = True
while run:
pygame.time.delay(500)
square = Square("crimson",x,200)
x+=50
screen.fill("cyan")
squares.add(square)
squares.update()
squares.draw(screen)
pygame.display.flip()
I tried switching up the orders of .fill() and .draw() but the outcome is consistently the same. Should not screen.fill("cyan") erase everything on the screen and drawing afterwards make the illusion of a square moving?
On each iteration, your main loop adds a sprite to your sprite group
squaresthat is 50 pixels to the right of the last sprite.Therefore, you don't have a single elongated rectangle, but rather multiple overlapping squares. Each square is 50 pixels to the right of its neighbor.
I think you meant to move your square instead. That means you need to:
update()method toclass Squarethat adds 50 pixels to the x-coordinate of aSquareobject's rectangle when called.Here is an example, tested with Python 3.10.5 and Pygame 2.5.2 on Windows 10: