Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

python - 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))
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...