淺談Python Pygame圖像的基本使用
笛卡爾坐標(biāo)系
游戲離不開坐標(biāo),我們來(lái)康康pygame中坐標(biāo)是如何設(shè)立的吧~
窗口左上角坐標(biāo)(0,0),橫軸正向向右,縱軸正向向下
實(shí)際效果
碰到邊框就返回(其實(shí)是小球碰撞實(shí)驗(yàn),我不愛(ài)用正經(jīng)的小球,所以…)
代碼
import pygame,sys pygame.init() size = width, height = 600, 400 speed = [1,1] BLACK = 0, 0, 0 s = pygame.display.set_mode(size) pygame.display.set_caption("hi 滑稽") ball = pygame.image.load("img/361.png") ballrect = ball.get_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 > height: speed[1] = - speed[1] s.fill(BLACK) s.blit(ball, ballrect) pygame.display.update()
代碼說(shuō)明
碰撞原理
方法說(shuō)明
方法 | 說(shuō)明 |
---|---|
pygame.image.load(filename) | 將filename路徑下的圖像載入游戲,支持JPG、PNG、GIF(非動(dòng)畫)等13種常用圖片格式 |
get_rect() | 返回一個(gè)覆蓋圖像的矩形Rect對(duì)象 |
move(x,y) | 矩形移動(dòng)一個(gè)偏移量(x,y),即在橫軸方向移動(dòng)x像素,縱軸方向移動(dòng)y像素,xy為整數(shù) |
fill(color) | 顯示窗口背景填充為color顏色,采用RGB色彩體系 |
blit(src, dest) | 將一個(gè)圖像繪制在另一個(gè)圖像上,即將src繪制到dest位置上。 |
載入圖片
pygame.init() size = width, height = 600, 400 #設(shè)置了寬高,也可以在pygame.display.set_mode()設(shè)置 speed = [1,1] #速度 BLACK = 0, 0, 0#顏色黑色 s = pygame.display.set_mode(size) pygame.display.set_caption("hi 滑稽") ball = pygame.image.load("img/361.png") #注意圖片路徑 ballrect = ball.get_rect()
surface對(duì)象和Rect對(duì)象
Rect對(duì)象屬性
Rect對(duì)象有一些重要屬性,例如:top,bottom,left,right表示上下左右width,height表示寬度、高度。
移動(dòng)
ballrect = ballrect.move(speed[0], speed[1])# x1 if ballrect.left < 0 or ballrect.right > width: # x2 speed[0] = - speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = - speed[1]
x1:矩形移動(dòng)一個(gè)偏移量(x,y),即在橫軸方向移動(dòng)x像素,縱軸方向移動(dòng)y像素,xy為整數(shù)x2:遇到左右兩側(cè),橫向速度取反;遇到上下兩側(cè),縱向速度取反。
到此這篇關(guān)于淺談Python Pygame圖像的基本使用的文章就介紹到這了,更多相關(guān)Pygame圖像的基本使用內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。