天天看點

Python 使用 pygame 實作一個簡單的動畫

首先安裝pygame庫:

$ sudo pip install pygame
           

測試安裝效果:

#導入pygame子產品
import pygame
#初始化pygame
pygame.init()
#建立舞台,利用Pygame中的display子產品,來建立視窗
screen = pygame.display.set_mode((640,480),0,32)
#設定視窗标題
pygame.display.set_caption("Hello PyGame")
           

這個時候大家運作就能得到一個視窗但是視窗一閃而過。

#導入pygame子產品
import pygame
#初始化pygame
pygame.init()
#建立舞台,利用Pygame中的display子產品,來建立視窗
screen = pygame.display.set_mode((640,480),0,32)
#設定視窗标題
pygame.display.set_caption("Hello PyGame")
while 1:
    for event in pygame.event.get():
    #這段程式大家可能比較費解,實際上是檢測quit事件
        if event.type == pygame.QUIT:
            pygame.quit()
           

實作一個左右滾動的小貓:

image.png

直接上代碼:

# 導入pygame子產品
import pygame

# 初始化pygame
pygame.init()
width = 844
height = 689
speed = 10
# 建立舞台,利用Pygame中的display子產品,來建立視窗
screen = pygame.display.set_mode((width, height), 0, 32)
# 設定視窗标題
pygame.display.set_caption("Hello PyGame")

# 我的cat.png和cat.py檔案在同一個檔案夾下面
# 是以可以直接這樣加載圖檔的
# laod函數加載圖檔
cat = pygame.image.load("cat.jpg")
print(cat)
cat_x, cat_y = 0, 0  # 貓的坐标
h_direction = 1  # 水準方向

while 1:
    for event in pygame.event.get():
        # 這段程式大家可能比較費解,實際上是檢測quit事件,實際講課中讓學生直接模仿即可,時間足夠也可以講明白
        if event.type == pygame.QUIT:
            pygame.quit()

    # blit函數的作用是把加載的圖檔放到舞台的(cat_x, cat_y)坐标的位置
    screen.blit(cat, (cat_x, cat_y))
    # 這樣就實作了會移動的貓
    cat_x += speed * h_direction
    # 如果貓的坐标超出了640,就讓小貓反向
    # 如果貓的坐标小于了0,也讓小貓反向,這樣就實作了碰到牆壁反彈的效果
    if cat_x > width:
        h_direction = -h_direction
    elif cat_x < 0:
        h_direction = -h_direction
    pygame.display.update()