本節課程主要講解樂Pygame的一些常用對象及操作,如果要深入了解,可以參考[Pygame官方文檔](http://www.pygame.org/docs/)。
## pygame簡介
Pygame提供使用圖形用戶界面或GUI創建程序的功能。使用基于圖形的GUI的程序可以代替基于文本的CLI顯示帶有圖像和顏色的窗口。
## 安裝pygame庫
在終端輸入命令,安裝Pygame庫:
```
sudo apt-get install python-pygame
```
## Hello world
```python
# helloworld.py
import pygame, sys # 導入所需的模塊
from pygame.locals import * # 導入所有pygame.locals里的變量
pygame.init() # 初始化pygame
screen = pygame.display.set_mode((500, 400)) # 設置窗口的大小,單位為像素
pygame.display.set_caption('Hellow World') # 設置窗口標題
while True: # 程序主循環
for event in pygame.event.get(): # 獲取事件
if event.type == QUIT: # 判斷事件是否為退出事件
pygame.quit() # 退出pygame
sys.exit() # 退出系統
pygame.display.update() # 繪制屏幕內容
```
運行效果
<div align="center"><img src="4.png"/><p id="color" style="color:red">4.png</p></div>
這里解釋上面程序的運行方式一個循環(主循環),做下面這三件事:
處理時間
更新游戲狀態
繪制游戲狀態到屏幕上
## 繪制圖形
Pygame的坐標原點(0, 0)點位于左上角,X軸自左向右,Y軸自上向下,單位位像素。這里介紹一下常用的方法:
|方法|方法描述|
|---|---|
pygame.draw.line(Surface, color, start_pos, end_pos, width) |此方法用于繪制一條線段
pygame.draw.aaline(Surface, color, start_pos, end_pos, blend) |此方法用于繪制一條抗鋸齒的線
pygame.draw.lines(Surface, color, closed, pointlist, width) |此方法用于繪制一條折線
pygame.draw.rect(Surface, color, Rect) |此方法用于繪制一個矩形
pygame.draw.rect(Surface, color, Rect, width) |此方法用于繪制一個矩形框
pygame.draw.ellipse(Surface, color, Rect, width) |此方法用于繪制一個橢圓框
pygame.draw.ellipse(Surface, color, Rect) |此方法用于繪制一個橢圓
pygame.draw.polygon(Surface, color, pointlist, width) |此方法用于繪制一個多邊形
pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width) |此方法用于繪制一條弧線
pygame.draw.circle(Surface, color, Rect, radius) |此方法用于繪制一個圓
以下為示例代碼:
```python
# drawing.py
# 導入需要的模塊
import pygame, sys
from pygame.locals import *
from math import pi
pygame.init() # 初始化pygame
screen = pygame.display.set_mode((400, 300)) # 設置窗口的大小,單位為像素
pygame.display.set_caption('Drawing') # 設置窗口標題
# 定義顏色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
screen.fill(WHITE) # 設置背景顏色
pygame.draw.line(screen, GREEN, [0, 0], [50, 30], 5) # 繪制一條線
pygame.draw.aaline(screen, GREEN, [0, 50], [50, 80], True) # 繪制一條抗鋸齒的線
pygame.draw.lines(screen, BLACK, False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5) #繪制一條直線
pygame.draw.rect(screen, BLACK, [75, 10, 50, 20], 2) #繪制一個空心矩形
pygame.draw.rect(screen, BLACK, [150, 10, 50, 20]) # 繪制一個矩形
# 繪制多條弧線
pygame.draw.arc(screen, BLACK, [210, 75, 150, 125], 0, pi/2, 2)
pygame.draw.arc(screen, GREEN, [210, 75, 150, 125], pi/2, pi, 2)
pygame.draw.arc(screen, BLUE, [210,75, 150, 125], pi, 3*pi/2, 2)
pygame.draw.arc(screen, RED, [210, 75, 150, 125], 3*pi/2, 2*pi, 2)
pygame.draw.circle(screen, BLUE, [60, 250], 40) # 繪制一個圓
while True: # 程序主循環:
for event in pygame.event.get(): # 獲取事件
if event.type == QUIT: # 判斷事件是否為退出事件
pygame.quit() # 退出pygame
sys.exit() # 退出系統
pygame.display.update() # 繪制屏幕內容
```
運行效果如下:
<div align="center"><img src="5.png"/><p id="color" style="color:red">5.png</p></div>
## 實現動畫
pygame實現動畫主要用到的方法:
|方法|方法描述|
|---|---|
pygame.image.load(filename)|加載一張圖片
pygame.Surface.blit(Source, dest, area= None, special_flags = 0)|將圖片繪制到屏幕相應坐標上(后面兩個參數默認,可以不傳)
pygame.time.Clock() |獲得pygame的時鐘
pygame.time.Clock.tick(FPS) |設置pygame時鐘的間隔時間
以下為示例代碼
```python
# animoation.py
# 導入需要的模塊
import pygame, sys
from pygame.locals import *
pygame.init() # 初始化pygame
FPS = 30 # 設置幀率(屏幕每秒刷新的次數)
fpsClock = pygame.time.Clock() # 獲得pygame的時鐘
pygame.display.set_mode((500, 400), 0, 32) # 設置窗口大小
pygame.display.set_caption('Animation') # 設置標題
WHITE = (255, 255, 255) # 定義顏色
img = pygame.image.load('resources/test.png') # 加載一張圖片(所用到的圖片參考1.5代碼獲取)
# 初始化圖片的位置
imgx = 10
imgy = 10
direction = 'right' # 初始化圖片的移動方向
while True: # 程序主循環
screen.fill(WHITE) # 每次都要重新繪制背景白色
# 判斷移動的方向,并對相應的坐標做加減
if direction == 'right':
imgx += 5
if imgx == 380:
direction = 'down'
elif direction == 'down':
imgy += 5
if imgy == 300:
direction = 'left'
elif direction == 'left':
imgx -= 5
if imgx == 10:
direction = 'up'
elif direction == 'up':
imgy -= 5
if imgy == 10:
direction = 'right'
screen.blit(img, (imgx, imgy)) # 該方法將用于圖片繪制到相應的坐標中
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update() # 刷新屏幕
fpsClock.tick(FPS) # 設置pygame時鐘的間隔時間
```
## 繪制文字
Pygame提供了很方便的方法使用.ttf字體文件,這樣我們就能很輕易的將文字繪制在屏幕上了。 主要用到的方法(以ARBERKLEY.ttf字體為例):
|方法|方法描述|
|---|---|
pygame.font.Font(filename, size) |創建字體對象
pygame.font.Font.render(text, antialias, color, background=None) |
.get_rect() |獲得一個對象的rect,以便于設置其坐標位置
以下為示例代碼:
```python
# font.py
# 導入需要的模塊
import pygame, sys
from pygame.locals import *
pygame.init() # 初始化pygame
screen = pygame.display.set_mode((500,400)) # 設置窗口的大小,單位為像素
pygame.display.set_caption('Font') # 設置窗口的標題
# 定義顏色
WHITE = (255, 255, 255)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 128)
fontObj = pygame.font.Font('resources/ARBERKLEY.ttf', 50) # 通過字體文件獲得字體對象
textSurfaceObj = fontObj.render('Pygame', True, BLUE, GREEN) # 配置要顯示的文字
textRectObj = textSurfaceObj.get_rect() # 獲得要顯示的對象的rect
textRectObj.center = (250, 200) # 設置顯示對象的坐標
screen.fill(WHITE) # 設置背景
screen.blit(textSurfaceObj, textRectObj) # 繪制字體
while True: # 程序主循環
for event in pygame.event.get(): # 獲取事件
if event.type == QUIT: # 判斷事件是否為退出事件
pygame.quit() # 退出pygame
sys.exit() # 退出系統
pygame.display.update() # 繪制屏幕內容
```
## 播放音頻
在Pygame里播放音頻有兩個方法,一個用來播放特效聲音,一個用來播放背景音樂:
|方法|方法描述
|---|---|
pygame.mixer.Sound(filename) |該方法返回一個Sound對象,調用它的.play( )方法,即可播放較短的音頻文件(比如玩家受到傷害、收集到金幣等)
pygame.mixer.music.load(filename) |該方法用來加載背景音樂pygame.mixer.music.play( )|調用方法就可以播放背景音樂(在同一個時刻只允許加載一個背景音樂)
以下為示例代碼:
```python
# audio.py
# 導入需要的模塊
import pygame, sys
from pygame.locals import *
pygame.init() # 初始化pygame
screen = pygame.display.set_mode((500,400)) # 設置窗口的大小,單位為像素
pygame.display.set_caption('Audio') # 設置窗口的標題
WHITE = (255, 255, 255) # 定義顏色
screen.fill(WHITE) # 設置背景
sound = pygame.mixer.Sound('resources/bounce.ogg') # 加載并播放一個特效音頻文件(所用到的音頻文件請參考1.5代碼獲取)
sound.play()
pygame.mixer.music.load('resources/bgmusic.mp3') # 加載背景音樂文件
# 播放背景音樂,第一個參數為播放的次數(-1表示無限循環),第二個參數是設置播放的起點(單位為秒)
pygame.mixer.music.play(-1, 0.0)
while True: # 程序主循環
for event in pygame.event.get(): # 獲取事件
if event.type == QUIT: # 判斷事件是否為退出事件
pygame.mixer.music.stop() # 停止播放背景音樂
pygame.quit() # 退出pygame
sys.exit() # 退出系統
pygame.display.update() # 繪制屏幕內容
```
## 事件
Pygame里常用的事件如下表:
|事件|產生途徑|參數
|---|---|---|
|QUIT| 用戶按下關閉按鈕 |none
ACTIVEEVENT| Pygame被激活或者隱藏| gain, state
|KEYDOWN |鍵盤被按下 |unicode, key, mod
KEYUP| 鍵盤被放開| key, mod
MOUSEMOTION| 鼠標移動| pos, rel, buttons
MOUSEBUTTONDOWN| 鼠標按下| pos, button
MOUSEBUTTONUP| 鼠標放開| pos, button
VIDEORESIZE| Pygame窗口縮放| size, w, h
以下為示例代碼:
```python
# event.py
# 導入需要的模塊
import pygame, sys
from pygame.locals import *
WHITE = (255, 255, 255) # 定義顏色
pygame.init() # 初始化pygame
screen = pygame.display.set_mode((500, 400), 0, 32) # 設置窗口的大小,單位為像素
pygame.display.set_caption('Event') # 設置窗口的標題
screen.fill(WHITE) # 設置背景
while True: # 程序主循環
for event in pygame.event.get(): # 獲取事件
if event.type == QUIT: # 判斷事件是否為退出事件
pygame.quit() # 退出pygame
sys.exit() # 退出系統
if event.type ==MOUSEMOTION: # 獲得鼠標當前的位置
print(event.pos)
if event.type ==MOUSEBUTTONDOWN: # 獲得鼠標按下的位置
print("鼠標按下:",event.pos)
if event.type ==MOUSEBUTTONUP: # 獲得鼠標抬起的位置
print("鼠標抬起:",event.pos)
if event.type == KEYDOWN: # 獲得鍵盤按下的事件
if(event.key==K_UP or event.key==K_w):
print("上")
if(event.key==K_DOWN or event.key==K_s):
print("下")
if(event.key==K_LEFT or event.key==K_a):
print("左")
if(event.key==K_RIGHT or event.key==K_d):
print("右")
if(event.key==K_ESCAPE): # 按下鍵盤的Esc鍵退出
pygame.quit() # 退出pygame
sys.exit() # 退出系統
pygame.display.update() # 繪制屏幕內容
```
pygame學習更多:https://www.pygame.org/docs/
- 前言
- 第一章 樹莓派快速入門
- 1. 初識樹莓派3B+
- 2. 燒錄系統
- 3. 樹莓派連接鍵盤鼠標和顯示器
- 4. 啟動樹莓派
- 5.樹莓派連接網絡
- 6. Windows遠程訪問樹莓派
- 7. 終端通過raspi-config配置樹莓派
- 第二章 樹莓派編程
- 1. Linux入門操作
- 常用的linux命令
- 重要的快捷鍵
- 通過命令安裝軟件
- 樹莓派關機/重啟
- 2. 創建、編輯和保存文件
- 3. 創建并運行Python程序
- 4. 使用樹莓派的GPIO口
- 第三章 樹莓派套件應用
- 樹莓派3B+ IO擴展板介紹
- 家居系統
- 會呼吸的RGB燈
- 樹莓派控制家電
- 制作一個環境檢測儀
- 樹莓派攝像頭做遠程監控
- 攝像頭使用
- socket通信
- PiCamera + socket遠程監控
- AI語音
- 配置snowboy
- 自定義響應
- 采集語音和語音播放
- 語音機器人
- 圖靈機器人
- 俄羅斯方塊小游戲
- pygame基本使用
- ADKeyboard使用
- 俄羅斯方塊實現原理
- 俄羅斯方塊代碼講解
- 手勢控制的樹莓派相冊
- 模塊介紹
- 爬取圖片
- 電子相冊
- 附錄
- 網址