上一篇我們已經(jīng)可以顯示靜態(tài)的圖像,接下來就要讓它們動起來。
一、飛機(jī)的移動

游戲顯示原理
通過觀察發(fā)現(xiàn),飛機(jī)向上移動,只是圖片的Y坐標(biāo)發(fā)生了變化。那我們先嘗試改變圖片坐標(biāo)。
import pygame
# 創(chuàng)建一個(gè)窗口
screen = pygame.display.set_mode((480, 852), 0, 32)
# 讀取背景圖片
Image_background = pygame.image.load("./res/background.png")
# 讀取飛機(jī)的圖片
Image_hero = pygame.image.load("./res/hero1.png")
# 把圖片貼到screen對象中
temp_y = 500
while True :
if temp_y < 0 :
temp_y = 500
temp_y -= 10
screen.blit(Image_background, (0, 0))
screen.blit(Image_hero, (200, temp_y))
pygame.display.update()

運(yùn)行可以看到飛機(jī)移動到頂部,再返回原位,如此循環(huán)
二、添加鍵盤控制
游戲區(qū)別于動畫,它還要響應(yīng)玩家的操作,接下來就給它添加鍵盤控制。
import pygame
from pygame.locals import *
# 創(chuàng)建一個(gè)窗口
screen = pygame.display.set_mode((480, 852), 0, 32)
# 讀取背景圖片
Image_background = pygame.image.load("./res/background.png")
# 讀取飛機(jī)的圖片
Image_hero = pygame.image.load("./res/hero1.png")
# 把圖片貼到screen對象中
temp_y = 500
while True :
for event in pygame.event.get(): #捕捉系統(tǒng)事件
if event.type == KEYDOWN : #篩選事件,KEYDOWN是鍵盤按鍵被按下
if event.key == K_UP: #按下"UP"鍵 Y坐標(biāo)變小
temp_y -= 5
elif event.key == K_DOWN:#按下"DOWN"鍵 Y坐標(biāo)變大
temp_y += 5
screen.blit(Image_background, (0, 0))
screen.blit(Image_hero, (200, temp_y))
pygame.display.update()
腳本邏輯比較簡單,效果就是按"UP"鍵(減小圖片Y坐標(biāo)) 飛機(jī)向上移動,按"DOWN"鍵 (增大圖片Y坐標(biāo)) 飛機(jī)向下移動。