Created multiple instances of the same image using a loop, can I move each instance of the image independently?

I have an image in pygame with multiple instances of the image called in a for loop. is there a way I could move each instance of the image independently without moving the others with the code as is? or will I have to load separate instances of the image individually?

def pawn(self): 
    y_pos = 100
    self.image = pygame.transform.scale(pygame.image.load('pawn.png'), (100,100))
    for x_pos in range(0,8,1):
        pieceNum = x_pos
        screen.blit(self.image, (x_pos*100, y_pos))

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I recommend to use pygame.sprite.Sprite and pygame.sprite.Group:

Create a class derived from pygame.sprite.Sprite:

class MySprite(pygame.sprite.Sprite):

    def __init__(self, image, pos_x, pos_y):
        super().__init__() 
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.topleft = (pos_x, pos_y)

Load the image

image = pygame.transform.scale(pygame.image.load('pawn.png'), (100,100))

Create a list of sprites

imageList = [MySprite(image, x_pos*100, 100) for x_pos in range(0,8,1)]

and create a sprite group:

group = pygame.sprite.Group(imageList)

The sprites of a group can be drawn by .draw (screen is the surface created by pygame.display.set_mode()):

group.draw(screen)

The position of the sprite can be changed by changing the position of the .rect property (see pygame.Rect).

e.g.

imageList[0].rect = imageList[0].rect.move(move_x, move_y)

Of course, the movement can be done in a method of class MySprite:

e.g.

class MySprite(pygame.sprite.Sprite):

    # [...]

    def move(self, move_x, move_y):
        self.rect = self.rect.move(move_x, move_y)
imageList[1].move(0, 100)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x