使用循环创建了同一图像的多个实例,我可以独立移动图像的每个实例吗?
我在 pygame 中有一个图像,其中包含在 for 循环中调用的多个图像实例.有没有一种方法可以独立移动图像的每个实例,而无需按原样使用代码移动其他实例?还是我必须单独加载图像的单独实例?
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))
我推荐使用 pygame.sprite.Sprite
和 pygame.sprite.Group
:
I recommend to use pygame.sprite.Sprite
and pygame.sprite.Group
:
创建一个派生自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)
加载图片
image = pygame.transform.scale(pygame.image.load('pawn.png'), (100,100))
创建精灵列表
imageList = [MySprite(image, x_pos*100, 100) for x_pos in range(0,8,1)]
并创建一个精灵组:
group = pygame.sprite.Group(imageList)
一组精灵可以通过.draw
绘制(screen
是pygame.display.set_mode()
创建的表面):
The sprites of a group can be drawn by .draw
(screen
is the surface created by pygame.display.set_mode()
):
group.draw(screen)
可以通过更改 .rect
属性的位置来更改精灵的位置(参见 pygame.Rect
).
The position of the sprite can be changed by changing the position of the .rect
property (see pygame.Rect
).
例如
imageList[0].rect = imageList[0].rect.move(move_x, move_y)
当然,移动可以在MySprite
类的方法中完成:
Of course, the movement can be done in a method of class MySprite
:
例如
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)