# 第二章:sprite 介紹 ## `pygame.sprite.Sprite` * ### 簡介: 是一個 *class*,用來給遊戲中的其他角色類別 **繼承** ,方便進行遊戲物件的管理。 * ### 必備成員變數: * `image`:圖像 * `rect`:位置與大小  * ### 預設成員函式: * `update()`:更新物件狀態,預設不做任何事,留給你自行定義。 * `kill()`:將它從所有群組中移除,用來刪除遊戲物件。 ## `pygame.sprite.Group()` * ### 簡介: 是一個管理 Sprite 的 **容器**,用來集中處理一堆 Sprite。 * ### 預設成員函式: * `add(*sprites)`:加入新的 Sprite 到 Group 中 * `update()`:呼叫 Group 內所有 Sprite 的 `update()` 函式 * `draw(surface)`:把每個 Sprite 的 image 畫到 rect 指定的位置 ## 範例 * ### 介紹: 1. 定義一個 Square 類別: * 初始設定: * 圖案為一個 50 * 50 的方形,顏色為藍色 * 中心位置設置指定的位置上 * 移動速度設為 5 * `update()` 函式: * 向右移動 * 若超出視窗右方,從左方出現 1. 用一個 `Group()` 管理創建出來的兩個 square 物件 2. 利用 `Group()` 將所有物件畫在視窗上 3. 利用 `Group()` 呼叫所有物件的 `update()` 函式 * ### 程式碼: ```python= import pygame FPS = 60 WIDTH, HEIGHT = 800, 700 WHITE = (255, 255, 255) BLUE = (0, 0, 255) pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("打磚塊遊戲") clock = pygame.time.Clock() # 定義 Square 類別 class Square(pygame.sprite.Sprite): def __init__(self, center): super().__init__() self.image = pygame.Surface((50, 50)) self.image.fill(BLUE) self.rect = self.image.get_rect() self.rect.center = center self.speed = 5 def update(self): self.rect.x += self.speed if self.rect.left >= WIDTH: self.rect.right = 0 all_sprites = pygame.sprite.Group() # 物件一 square1 = Square((200, 200)) all_sprites.add(square1) # 物件二 square2 = Square((400, 400)) all_sprites.add(square2) running = True while running: clock.tick(FPS) # 輸入處理 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 更新遊戲 all_sprites.update() # 畫面顯示 screen.fill(WHITE) all_sprites.draw(screen) pygame.display.update() pygame.quit() ``` * ### 語法說明: * `pygame.Surface(size)`:創建一個矩形平面 * `surface.image.get_rect()`:取得平面的 rect
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up