2017-06-30 24 views
1

我想知道如何在屏幕上繪製一個包含精靈和特定行和列的矩陣。這是我的代碼到目前爲止:如何在python中添加一個精靈矩陣到屏幕上

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

創建pygame.sprite.Group實例和矩陣添加到它:

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

要更新和繪製所有包含精靈,只需撥打all_sprites.update()(調用的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。

+0

[這裏是sprite/sprite組教程。](http://programarcadegames.com/index.php?chapter=introduction_to_sprites&lang=de#section_13) – skrx

相關問題