python Pygame的具體使用講解

源碼及資料下載:http://labfile.oss.aliyuncs.com/courses/940/foundation.zip

1.HelloWorld

# -*- coding: UTF-8 -*-
# helloworld.py

# 導入所需的模塊
import pygame, sys
# 導入所有pygame.locals裏的變量(比如下面大寫的QUIT變量)
from pygame.locals import *


# 初始化pygame
pygame.init()

# 設置窗口的大小,單位爲像素
screen = pygame.display.set_mode((500, 400))

# 設置窗口標題
pygame.display.set_caption('Hello World')

# 程序主循環
while True:

  # 獲取事件
  for event in pygame.event.get():
    # 判斷事件是否爲退出事件
    if event.type == QUIT:
      # 退出pygame
      pygame.quit()
      # 退出系統
      sys.exit()

  # 繪製屏幕內容
  pygame.display.update()

效果圖如下:

 

這裏解釋一下上面程序的運行方式

一個遊戲循環(也可以稱爲主循環)就做下面這三件事:

  1. 處理事件
  2. 更新遊戲狀態
  3. 繪製遊戲狀態到屏幕上

 

2 繪製圖形

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)此方法用於繪製一個橢圓

pygame.draw.ellipse(Surface, color, Rect, width)此方法用於繪製一個橢圓框

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)此方法用於繪製一個圓

以下爲示例代碼:

# -*- coding: UTF-8 -*-
# drawing.py

# 導入需要的模塊
import pygame, sys
from pygame.locals import *
from math import pi


# 初始化pygame
pygame.init()

# 設置窗口的大小,單位爲像素
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.ellipse(screen, RED, [225, 10, 50, 20], 2)

# 繪製一個橢圓
pygame.draw.ellipse(screen, RED, [300, 10, 50, 20])

# 繪製多邊形
pygame.draw.polygon(screen, BLACK, [[100, 100], [0, 200], [200, 200]], 5)

# 繪製多條弧線
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
      pygame.quit()
      # 退出系統
      sys.exit()

  # 繪製屏幕內容
  pygame.display.update()

效果圖如下:

3 實現動畫

由於人類眼睛的特殊生理結構,當所看畫面的幀率高於24的時候,就會認爲是連貫的,此現象稱之爲 視覺暫留 。

幀率(Frame rate)是用於測量顯示幀數的量度,所謂的測量單位爲每秒顯示幀數(Frames per Second,簡稱:FPS)

一般來說30fps是可以接受的,但是將性能提升至60fps則可以明顯提升交互感和逼真感,但是一般來說超過75fps一般就不容易察覺到有明顯的流暢度提升了。

在我們原有座標系的基礎上添加偏移量,再重新繪製,依次一張一張的循環繪製下去,就會得到我們想要的物體移動的效果。

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時鐘的間隔時間

以下爲示例代碼:

# -*- coding: UTF-8 -*-
# animation.py

# 導入需要的模塊
import pygame, sys
from pygame.locals import *

# 初始化pygame
pygame.init()

# 設置幀率(屏幕每秒刷新的次數)
FPS = 30

# 獲得pygame的時鐘
fpsClock = pygame.time.Clock()

# 設置窗口大小
screen = pygame.display.set_mode((500, 400), 0, 32)

# 設置標題
pygame.display.set_caption('Animation')

# 定義顏色
WHITE = (255, 255, 255)

# 加載一張圖片(所用到的的圖片請參考1.5代碼獲取)
img = pygame.image.load('resources/shiyanlou.PNG')

# 初始化圖片的位置
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()

  # 設置pygame時鐘的間隔時間
  fpsClock.tick(FPS)

 

效果圖如下:

4 繪製文字 

如果你想繪製文字到屏幕上,Pygame提供了很方便的方法使用.ttf字體文件,這樣我們就能很輕易的將文字繪製在屏幕上了。

這裏我使用了ARBERKLEY.ttf作爲字體,字體文件的獲取請參考1.5代碼獲取。

主要用到的方法:

pygame.font.Font(filename, size)

filename:字體文件的文件名;

size:字體的高height,單位爲像素;

pygame.font.Font.render(text, antialias, color, background=None)

text:要顯示的文字;

antialias: 是否抗鋸齒;

color:字體顏色;

background:背景顏色(可選參數);

.get_rect()

獲得一個對象的rect,以便於設置其座標位置

以下爲示例代碼:

# -*- coding: UTF-8 -*-
# font.py

# 導入需要的模塊
import pygame, sys
from pygame.locals import *

# 初始化pygame
pygame.init()

# 設置窗口的大小,單位爲像素
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)

# 獲得要顯示的對象的rect
textRectObj = textSurfaceObj.get_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
      pygame.quit()
      # 退出系統
      sys.exit()

  # 繪製屏幕內容
  pygame.display.update()

效果圖如下:

 

 

5.播放音頻

在Pygame裏播放音頻有兩個方法,一個用來播放特效聲音,一個用來播放背景音樂:

pygame.mixer.Sound(filename)

該方法返回一個Sound對象,調用它的.play( )方法,即可播放較短的音頻文件(比如玩家受到傷害、收集到金幣等);

pygame.mixer.music.load(filename)

該方法用來加載背景音樂,之後調用pygame.mixer.music.play( )方法就可以播放背景音樂(Pygame只允許加載一個背景音樂在同一個時刻)

以下爲示例代碼:

# -*- coding: UTF-8 -*-
# audio.py

# 導入需要的模塊
import pygame, sys
from pygame.locals import *

# 初始化pygame
pygame.init()

# 設置窗口的大小,單位爲像素
screen = pygame.display.set_mode((500,400))

# 設置窗口的標題
pygame.display.set_caption('Audio')

# 定義顏色
WHITE = (255, 255, 255)

# 設置背景
screen.fill(WHITE)

# 加載並播放一個特效音頻文件(所用到的音頻文件請參考1.5代碼獲取)
sound = pygame.mixer.Sound('resources/bounce.ogg')
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
      pygame.quit()
      # 退出系統
      sys.exit()

  # 繪製屏幕內容
  pygame.display.update()

6.事件

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

以下爲示例代碼:

# -*- coding: UTF-8 -*-
# event.py

# 導入需要的模塊
import pygame, sys
from pygame.locals import *

# 定義顏色
WHITE = (255, 255, 255)

# 初始化pygame
pygame.init()

# 設置窗口的大小,單位爲像素
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
      pygame.quit()
      # 退出系統
      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("右")
      # 按下鍵盤的Esc鍵退出
      if(event.key==K_ESCAPE):
        # 退出pygame
        pygame.quit()
        # 退出系統
        sys.exit()

  # 繪製屏幕內容
  pygame.display.update()

 效果圖如下:

若想要深入瞭解,可參考下方Pygame官方文檔的鏈接。

https://www.pygame.org/docs/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章