
- Pygame 教程
- Pygame - 主頁
- Pygame - 概述
- Pygame - Hello World
- Pygame - 顯示模式
- Pygame - Locals 模組
- Pygame - 顏色物件
- Pygame - 事件物件
- Pygame - 鍵盤事件
- Pygame - 滑鼠事件
- Pygame - 繪製形狀
- Pygame - 載入影像
- Pygame - 在視窗中顯示文字
- Pygame - 移動影像
- Pygame - 使用小鍵盤移動
- Pygame - 使用滑鼠移動
- Pygame - 移動矩形物件
- Pygame - 使用文字作為按鈕
- Pygame - 變換影像
- Pygame - 聲音物件
- Pygame - 混音器通道
- Pygame - 播放音樂
- Pygame - 播放電影
- Pygame - 使用相機模組
- Pygame - 載入游標
- Pygame - 訪問光碟
- Pygame - 精靈模組
- Pygame - PyOpenGL
- Pygame - 錯誤和異常
- Pygame 實用資源
- Pygame - 快速指南
- Pygame - 實用資源
- Pygame - 討論
Pygame - 移動影像
物件的移動是任何電腦遊戲的重要方面。電腦遊戲透過繪製和擦除物件在增量位置來建立移動的錯覺。以下程式碼透過在事件迴圈中遞增 x 座標位置來繪製圖像,並用背景色擦除它。
示例
image_filename = 'pygame.png' import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((400,300), 0, 32) pygame.display.set_caption("Moving Image") img = pygame.image.load(image_filename) x = 0 while True: screen.fill((255,255,255)) for event in pygame.event.get(): if event.type == QUIT: exit() screen.blit(img, (x, 100)) x= x+0.5 if x > 400: x = x-400 pygame.display.update()
輸出
Pygame 徽標影像開始顯示在左邊界並在反覆向右移動。如果它到達右邊界,它的位置將重置到左邊界。

在以下程式中,該影像一開始顯示在 (0,150) 位置。當用戶按箭頭鍵(左、右、上、下)時,影像透過 5 個畫素改變其位置。如果發生 KEYDOWN 事件,程式檢查鍵值是否為 K_LEFT、K_RIGHT、K_UP 或 K_DOWN。如果它是 K_LEFT 或 K_RIGHT,則 x 座標改變 +5 或 -5。如果鍵值是 K_UP 或 K_DOWN,則 y 座標的值改變 -5 或 +5。
image_filename = 'pygame.png' import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_caption("Moving with arrows") img = pygame.image.load(image_filename) x = 0 y= 150 while True: screen.fill((255,255,255)) screen.blit(img, (x, y)) for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == KEYDOWN: if event.key == K_RIGHT: x= x+5 if event.key == K_LEFT: x=x-5 if event.key == K_UP: y=y-5 if event.key == K_DOWN: y=y+5 pygame.display.update()
廣告