使用循环创建了同一图像的多个实例,我可以独立移动图像的每个实例吗? [英] Created multiple instances of the same image using a loop, can I move each instance of the image independently?

查看:37
本文介绍了使用循环创建了同一图像的多个实例,我可以独立移动图像的每个实例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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.Spritepygame.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绘制(screenpygame.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)

这篇关于使用循环创建了同一图像的多个实例,我可以独立移动图像的每个实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆