Pygame - 精靈模組



在我們遊戲視窗中繪製的任何可以四處移動的點陣圖都稱為精靈。pygame.sprite 模組包含在遊戲開發中非常有用的類和功能。除了用於建立精靈物件集合的精靈類之外,還有一些函式可以實現精靈物件的碰撞檢測。

精靈類作為遊戲中不同物件的基類。你可能需要將多個物件放入組中。為此,也提供了組類。

讓我們首先透過子類化 sprite.Sprite 類來開發一個精靈類。這個 Block 類的每個物件都是一個填充黑色矩形的塊。

class Block(pygame.sprite.Sprite):

   def __init__(self, color, width, height):
      super().__init__()

      self.image = pygame.Surface([width, height])
      self.image.fill(color)

      self.rect = self.image.get_rect()

我們將建立 50 個塊物件並將它們放入列表中。

for i in range(50):
   block = Block(BLACK, 20, 15)

   # Set a random location for the block
   block.rect.x = random.randrange(screen_width)
   block.rect.y = random.randrange(screen_height)
   
   # Add the block to the list of objects
   block_list.add(block)
   all_sprites_list.add(block)

我們建立一個紅色塊,將其稱為 player,並將其新增到列表中。

# Create a RED player block
player = Block(RED, 20, 15)
all_sprites_list.add(player)

在遊戲的事件迴圈中,檢測紅色塊 (player) 在隨滑鼠移動的同時與黑色塊的碰撞,並計算碰撞次數。

示例

事件迴圈程式碼如下:

while not done:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         done = True
   
   # Clear the screen
   screen.fill(WHITE)

   # Get the current mouse position. This returns the position
   # as a list of two numbers.
   pos = pygame.mouse.get_pos()

   # Fetch the x and y out of the list,
      # just like we'd fetch letters out of a string.
   # Set the player object to the mouse location
   player.rect.x = pos[0]
   player.rect.y = pos[1]

   # See if the player block has collided with anything.
   blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)

   # Check the list of collisions.
   for block in blocks_hit_list:
      score += 1
      print(score)

   # Draw all the spites
   all_sprites_list.draw(screen)

   # Go ahead and update the screen with what we've drawn.
   pygame.display.flip()

   # Limit to 60 frames per second
   clock.tick(60)

pygame.quit()

輸出

執行上面的程式碼。移動 player 塊以捕獲儘可能多的黑色塊。分數將回顯在控制檯上。

Sprite Module
廣告