pygame庫的安裝 pip install pygame
pygame最小開發框架
#Pygame Hello World Game import pygame,sys #引入pygame和sys(python標准庫) pygame.init() #初始化模塊創建及變量及設置,默認調用 screen = pygame.display.set_mode((600,400)) #初始化顯示窗口,元祖值為寬高 pygame.display.set_caption("Python游戲之旅") #窗體標題設置 #獲取事件並逐類響應 while True: #無限循環,直到python運行時退出結束 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() #游戲退出 pygame.display.update() #刷新屏幕
最小開發框架圖示:
壁球小游戲(展示型)與圖像的基本使用
1)壁球:游戲需要一個壁球,通過圖片引入(小球圖片位置:https://python123.io/PY15/PYG02-ball.gif)
2)壁球運動:壁球要能夠上下左右移動
3)壁球反彈:壁球要能夠在上下左右邊緣反彈
笛卡爾坐標系圖示:
反彈:
與邊緣垂直的速度改為反方向運動即 S=-S
壁球小游戲(展示型)代碼:
import pygame,sys pygame.init() size = width,hight = 600,400 speed = [1,1] BLACK = 0,0,0 screen = pygame.display.set_mode(size) pygame.display.set_caption("Pygame壁球") ball = pygame.image.load("PYG02-ball.gif") #將()中路徑下的圖像載入游戲,支持jpg、png、gif等13種常見格式 ballrect = ball.get_rect()#pygame使用內部定義的Surface對象表示所有載入的圖像,.get_rect()方法返回一個覆蓋圖像的矩形Rect對象 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed[0],speed[1]) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > hight: speed[1] = -speed[1] screen.fill(BLACK) screen.blit(ball,ballrect) pygame .display.update()
ball = pygame.image.load("PYG02-ball.gif")
#將()中路徑下的圖像載入游戲,支持jpg、png、gif等13種常見格式
ballrect = ball.get_rect()
#pygame使用內部定義的Surface對象表示所有載入的圖像,.get_rect()方法返回一個覆蓋圖像的矩形Rect對象
Rect對象
Rect對象有一些重要屬性,例如:
top,bottom,left,right表示上下左右
width,height表示寬度、高度
ballrect.move(x,y)
矩形移動一個偏移量(x,y),即在橫軸方向移動x像素,縱軸方向移動y像素,xy為整數
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > hight:
speed[1] = -speed[1]
遇到左右兩側,橫向速度取反;
遇到上下兩側,縱向速度取反;
screen.fill(color)
顯示窗口背景填充為color的顏色,采用RGB色彩體系。由於壁球在不斷運動,
運動后原有位置將默認填充白色,因此要不斷刷新背景色
screen.blit(src,dest)
將一個圖像繪制在另一個圖像上,即將src繪制到dest位置上。通過Rect對象一道對壁球的繪制。
(讓圖像跟着矩形移動而移動)
未完待續 ... ...
本文為博主學習筆記,轉載需注明來源;
學習視頻所屬:中國大學MOOC 北京理工大學 嵩天 黃天羽老師https://www.icourse163.org/course/BIT-1001873001