1 環境安裝 。
遊戲模塊導入:
直接去cmd下 pip install pygame
多試幾次 ,可能會因爲網速原因出現錯誤 , 多來幾次 就好了。
1 什麼是Surface 對象?
就是 pygame 中表示圖像的對象。
2 將一個對象移動到另一個圖像之上是怎麼回事?
pygame 每一時刻展示一個圖像 。 每個圖像是由像素組成的
blit方法將一個圖像放到另一個圖像上: 其實pygame並不是真正的移動的。 他只將部分區域替換成另一個圖像了。
3 移動圖像是怎麼回事?
這是個幀率的問題:
幀 : 一幅圖像
幀率: 一秒鐘可以切換多少幀
pygame每秒切換40-200幀
4 如何控制移動速度?
採用延遲time.delay(ms)
也可以用幀率來控制:
clock = pygame.time.Clock()
clock.tick(20)
5 pygame 效率高不高?
python 簡潔好用 但是效率不高
pygame 考慮了 效率, 於是內部好多模塊用C語言來實現的。
6 怎麼獲取幫助 ?
www.pygame.org官網
來看一個 樣例
代碼如下
import pygame
import sys
#初始化:啓動遊戲相關功能
pygame.init()
size = width,height = 800, 500#tuple
speed =[-2,1]#速度和初始方向:
bg = (255,255,255)#背景色
#設置指定大小的窗口Surface
screen = pygame.display.set_mode(size)
#設置窗口標題
pygame.display.set_caption('初次見面,多多關照')
#加載圖片Surface對象
photo = pygame.image.load('link.jpg')
#獲得圖像的位置矩形facele
position = photo.get_rect()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()#退出遊戲 右上角X
#移動圖像
position = position.move(speed)
#碰撞檢測:水平方向
if position.left < 0 or position.right > width:
#翻轉圖像 翻轉誰, 水平翻轉嗎? 垂直翻轉嗎?
photo = pygame.transform.flip(photo, True, False)
# 水平翻轉 :反方向移動
speed[0] = -speed[0]
#碰撞檢測:垂直方向
if position.top < 0 or position.bottom > height:
speed[1] = -speed[1]
#背景填充
screen.fill(bg)
#更新背景:將photo對象畫在screen對象上的position位置
screen.blit(photo,position)
#更新界面;flip刷新 pygame是雙緩衝的,將寫好的對象放在屏幕上,防止閃爍現象,就是刷新過快導致的。
pygame.display.flip()
#設置移動延遲 ms
pygame.time.delay(5)
2 加入鍵盤控制移動
import pygame
import sys
from pygame.locals import *
#初始化
pygame.init()
size = width,height = 1000, 600#tuple
speed =[-2,1]
bg = (255,255,255)#背景色
#設置指定大小的窗口Surface
screen = pygame.display.set_mode(size)
#設置窗口標題
pygame.display.set_caption('初次見面,多多關照')
#加載圖片Surface對象
photo = pygame.image.load('link.jpg')
#獲得圖像的位置矩形rectangle
position = photo.get_rect()
photo = photo = pygame.transform.flip(photo, True, False)
r_head = photo
l_head = photo = pygame.transform.flip(photo, True, False)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()#退出遊戲 右上角X
if event.type == KEYDOWN:
if event.key == K_LEFT:
speed = [-1,0]
photo = l_head
if event.key == K_RIGHT:
speed = [1,0]
photo = r_head
if event.key == K_UP:
speed = [0,-1]
if event.key == K_DOWN:
speed = [0,1]
#移動圖像
position = position.move(speed)
#碰撞檢測:水平方向
if position.left < 0 or position.right > width:
#翻轉圖像 翻轉誰, 水平翻轉嗎? 垂直翻轉嗎?
photo = pygame.transform.flip(photo, True, False)
# 水平翻轉 :反方向移動
speed[0] = -speed[0]
#碰撞檢測:垂直方向
if position.top < 0 or position.bottom > height:
speed[1] = -speed[1]
#背景填充
screen.fill(bg)
#更新背景
screen.blit(photo,position)
#更新界面
pygame.display.flip()
#設置延遲
pygame.time.delay(1)