如何在python

时间:2017-06-30 23:24:58

标签: python matrix pygame

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

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()

除了我不知道如何用精灵将这个矩阵绘制到屏幕上。有帮助吗? 这也是我的敌人课程:

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

1 个答案:

答案 0 :(得分:1)

创建一个pygame.sprite.Group实例并将矩阵添加到其中:

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

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

请注意,您的矩阵仅包含对choices列表中两个敌方实例的引用。如果你想要独特的精灵实例,你可以改变你的代码:

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。