Pgzero:用 Python 進(jìn)行游戲開發(fā)
1. pgzero
python在各個領(lǐng)域都有著豐富的第三方庫,pygame是python在游戲領(lǐng)域的應(yīng)用庫,可以用來開發(fā)各種不同的游戲。但是對于初學(xué)者來說,還是存在一定的門檻。
而今天要和大家分享的pgzero(pygame zero)是在pygame基礎(chǔ)上做了進(jìn)一步的封裝,使得設(shè)計一款游戲十分的方便,特別適合少兒編程領(lǐng)域的教學(xué), 與scratch相得益彰。
- pgzero的安裝
 
- pip install pygame
 - pip install pgzero
 
2. 游戲設(shè)計的過程
我們可以簡單梳理下開發(fā)一款簡單游戲需要的過程:
- 游戲的故事設(shè)計
 - 游戲的場景繪制(背景圖片和聲音)
 - 游戲的角色
 - 如何控制角色
 - 如何判斷成功與失敗
 - 游戲的關(guān)卡設(shè)計
 
3. pgzero基礎(chǔ)
pgzero游戲開發(fā)的過程如下:
- 游戲屏幕區(qū)域screen pgzero中游戲界面窗口設(shè)置由全局變量和內(nèi)置對象screen來完成:
    
- 窗口外觀:WIDTH , HEIGHT 和TITLE
 - 窗口清楚:screen.clear()
 - 窗口背景顏色:screen.fill((red, green, blue))
 - 在窗口繪制圖像:screen.blit(image, (left, top))
 - 在窗口繪制幾何圖案:screen.draw.line screen.draw.circle screen.draw.rect
 
 - 游戲角色Actor pgzero中所有以圖片顯示的元素都是Actor類來定義。
 
- # 'alien' 表示alien圖片,默認(rèn)是images/alien.png
 - # (50, 50) 定義了Actor在窗口上顯示的位置
 - alien = Actor('alien', (50, 50))
 
Actor的位置:
Actor重要屬性和方法:
- 其他屬性同pygame.Rect
    
- 外觀:image, 如alien.image = 'alien_hurt'
 - 位置: piex坐標(biāo)值:x,y, 設(shè)置位置:pos,left/right/top/bottom
 - 角度:angle
 - 繪制f方法:draw()
 - 距離方法: Actor.distance_to(target)
 - 角度方法:Actor.angle_to(target)
 
 - 游戲渲染繪制draw
 - 游戲狀態(tài)的更新update
 - 游戲外部事件的觸發(fā)控制on_xxx_xxx pgzero提供了常用的鼠標(biāo)和鍵盤事件
 
鍵盤的按鍵信息是通過keyboard內(nèi)置對象獲取的,鼠標(biāo)是mouse來獲取的,如:
- keyboard.a # The 'A' key
 - keyboard.left # The left arrow key
 - keyboard.rshift # The right shift key
 - keyboard.kp0 # The '0' key on the keypad
 - keyboard.k_0 # The main '0' key
 - mouse.LEFT
 - mouse.RIGHT
 - mouse.MIDDLE
 
詳見
- https://pygame-zero.readthedocs.io/en/stable/hooks.html#mouse.WHEEL_DOWN
 - 鍵盤事件:on_key_down, on_key_up
 - 鼠標(biāo)事件:on_mouse_down, on_mouse_up, on_mouse_move
 
其他重要元素
- 聲音 sounds:支持wav和ogg, 資源對象目錄默認(rèn)為./sounds
 
- # 播放聲音./sounds/drum.wav
 - sounds.drum.play()
 
- 音樂 music: 支持mp3, 主要是時間較長的音頻文件。資源對象目錄默認(rèn)為./music
 
- # 播放聲音./music/drum.mp3
 - music.play('drum')
 
- 動畫效果Animations,如移動角色到某個位置
 
- # animate(object, tween='linear', duration=1, on_finished=None, **targets)
 - animate(alien, pos=(100, 100))
 
詳見:
https://pygame-zero.readthedocs.io/en/stable/builtins.html#Animations
4. pgzero游戲例子
了解了pgzero的基本使用情況,下面來舉一個例子,將游戲編寫制作的過程串起來。
我們來模擬手機(jī)上的一款游戲FlappyBird。游戲簡單操作說明
在《FlappyBird》這款游戲中,玩家只需要用一根手指來操控,點(diǎn)擊觸摸屏幕,小鳥就會往上飛,不斷的點(diǎn)擊就會不斷的往高處飛。放松手指,則會快速下降。所以玩家要控制小鳥一直向前飛行,然后注意躲避途中高低不平的管子。 [3]
1、在游戲開始后,點(diǎn)擊屏幕,要記住是有間歇的點(diǎn)擊屏幕,不要讓小鳥掉下來。
2、盡量保持平和的心情,點(diǎn)的時候不要下手太重,盡量注視著小鳥。
3、游戲的得分是,小鳥安全穿過一個柱子且不撞上就是1分。當(dāng)然撞上就直接掛掉,只有一條命。
pgzero游戲代碼結(jié)構(gòu):
- import pgzrun
 - # 全局變量和初始化信息
 - TITLE = 'xxx'
 - WIDTH = 400
 - HEIGHT = 500
 - # 繪制游戲元素
 - def draw():
 - pass
 - # 更新游戲狀態(tài)
 - def update():
 - pass
 - # 處理鍵盤事件
 - def on_key_down():
 - pass
 - # 處理鍵盤事件
 - def on_mouse_down():
 - pass
 - # 執(zhí)行
 - pgzrun.go()
 
- import pgzrun
 - import random
 - TITLE = 'Flappy Bird'
 - WIDTH = 400
 - HEIGHT = 500
 - # These constants control the difficulty of the game
 - GAP = 130
 - GRAVITY = 0.3
 - FLAP_STRENGTH = 6.5
 - SPEED = 3
 - # bird
 - bird = Actor('bird1', (75, 200))
 - bird.dead = False
 - bird.score = 0
 - bird.vy = 0
 - storage = {}
 - storage['highscore'] = 0
 - def reset_pipes():
 - # 設(shè)置隨機(jī)的高度
 - pipe_gap_y = random.randint(200, HEIGHT - 200)
 - pipe_top.pos = (WIDTH, pipe_gap_y - GAP // 2)
 - pipe_bottom.pos = (WIDTH, pipe_gap_y + GAP // 2)
 - pipe_top = Actor('top', anchor=('left', 'bottom'))
 - pipe_bottom = Actor('bottom', anchor=('left', 'top'))
 - reset_pipes() # Set initial pipe positions.
 - def update_pipes():
 - # 不斷的移動柱子
 - pipe_top.left -= SPEED
 - pipe_bottom.left -= SPEED
 - if pipe_top.right < 0:
 - reset_pipes()
 - if not bird.dead:
 - bird.score += 1
 - if bird.score > storage['highscore']:
 - storage['highscore'] = bird.score
 - def update_bird():
 - # 小鳥下降
 - uy = bird.vy
 - bird.vy += GRAVITY
 - bird.y += (uy + bird.vy) / 2
 - bird.x = 75
 - # 根據(jù)小鳥死亡切換小鳥的造型
 - if not bird.dead:
 - if bird.vy < -3:
 - bird.image = 'bird2'
 - else:
 - bird.image = 'bird1'
 - # 判斷小鳥死亡: 是否觸碰柱子
 - if bird.colliderect(pipe_top) or bird.colliderect(pipe_bottom):
 - bird.dead = True
 - bird.image = 'birddead'
 - # 小鳥超過邊界 初始化
 - if not 0 < bird.y < 720:
 - bird.y = 200
 - bird.dead = False
 - bird.score = 0
 - bird.vy = 0
 - reset_pipes()
 - def update():
 - update_pipes()
 - update_bird()
 - # 按下任意鍵, 小鳥上升
 - def on_key_down():
 - if not bird.dead:
 - bird.vy = -FLAP_STRENGTH
 - #
 - def draw():
 - # 背景圖片
 - screen.blit('background', (0, 0))
 - # 加載小鳥/柱子
 - pipe_top.draw()
 - pipe_bottom.draw()
 - bird.draw()
 - # 顯示分?jǐn)?shù)和最佳
 - screen.draw.text(
 - str(bird.score),
 - color='white',
 - midtop=(WIDTH // 2, 10),
 - fontsize=70,
 - shadow=(1, 1)
 - )
 - screen.draw.text(
 - "Best: {}".format(storage['highscore']),
 - color=(200, 170, 0),
 - midbottom=(WIDTH // 2, HEIGHT - 10),
 - fontsize=30,
 - shadow=(1, 1)
 - )
 - pgzrun.go()
 
5. 總結(jié)
本文分享了基于pygame封裝版的pgzero開發(fā)python游戲的過程,希望對您有幫助。總結(jié)如下:
- pgzero開發(fā)三劍客:draw() / update() / on_xxx_xxx()
 - pgzero內(nèi)置對象:screen負(fù)責(zé)窗口設(shè)置,Actor負(fù)責(zé)圖像顯示,sounds負(fù)責(zé)短音頻,music負(fù)責(zé)長音頻bgm,動畫效果有animate
 - pgzero資源目錄:./images/xxx.png ./music/xxx.mp3 ./sounds/xxx/wav
 
6. 參考資料
https://pygame-zero.readthedocs.io/en/stable/


















 
 
 



 
 
 
 