python - 如何在Python中将 Sprite 矩阵添加到屏幕上

标签 python matrix pygame

我想知道如何在屏幕上绘制一个带有 Sprite 和特定行和列的矩阵。这是到目前为止我的代码:

rows = 3
cols = 6
choices = [Enemy(), Enemy2()]

def create_enemies():
matrix = [[np.random.choice(choices) for i in range(cols)] for j in range(rows)]
create_enemies()

除了我不知道如何将这个带有 Sprite 的矩阵绘制到屏幕上。有什么帮助吗? 这也是我的敌人类别:

class Enemy(pygame.sprite.Sprite):
    speed = 2
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([40, 40])
        self.image = pygame.image.load("images/e1.png").convert_alpha()
        self.rect = self.image.get_rect(center=(40,40))
        self.rect.x = 0
        self.rect.y = 0
    def update(self):
        self.rect.y += 1

class Enemy2(pygame.sprite.Sprite):
    speed = 2
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([40, 40])
        self.image = pygame.image.load("images/e2.png").convert_alpha()
        self.rect = self.image.get_rect(center=(40,40))
        self.rect.x = 0
        self.rect.y = 0
    def update(self):
        self.rect.y += 1

最佳答案

创建 pygame.sprite.Group实例并向其中添加矩阵:

all_sprites = pygame.sprite.Group()
all_sprites.add(matrix)

要更新和绘制所有包含的 Sprite ,只需调用 all_sprites.update() (调用 Sprite 的 update 方法)和 all_sprites.draw(screen ) 在你的主循环中。

<小时/>

请注意,您的矩阵仅包含对选择列表中两个敌人实例的引用。如果您想要独特的 Sprite 实例,请像这样更改代码:

choices = [Enemy, Enemy2]  # Contains references to the classes now.
# Create new instances in the list comprehension.
matrix = [[random.choice(choices)() for i in range(cols)] for j in range(rows)]

似乎没有理由使用 numpy。

关于python - 如何在Python中将 Sprite 矩阵添加到屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44855947/

相关文章:

Python py2exe 一体机

python - 如何避免Pygame将女性声音转换为男性

python - Java 网关进程在向驱动程序发送其端口号之前退出

Python 文件附加错误

arrays - 使用逻辑数组索引到矩阵

python - 属性错误 : 'numpy.int32' object has no attribute 'append'

python - 在背景中绘制随机星星,pygame

python - GAE(AppEngine)似乎在发布后调整了我的图像大小

python - 按字母顺序排列 Python 中的多行值列表?

arrays - Emacs 和 LaTeX : amount of columns for tables/matrices/arrays