1.在創(chuàng)建的窗口內(nèi)創(chuàng)建文字并顯示
創(chuàng)建窗口
import pygame
pygame.init()
screen=pygame.display.set_mode((600,400))
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
exit()
其中(600,400)位窗口大小
創(chuàng)建字體對象(找一只筆)
創(chuàng)建系統(tǒng)字體
SysFont(name, size, bold=False, italic=False)
name -> 字體名
size -> 字體大小
bold -> 加粗
italic -> 傾斜
font = pygame.font.SysFont('宋體', 22)
也可以創(chuàng)建自定義字體,需要自己下載添加
font = pygame.font.Font('./font/HYShangWeiShouShuW.ttf', 22)
根據(jù)字體創(chuàng)建文字去顯示對象(文字)
render(self, text, antialias, color, background=None)
text -> 要顯示的文字內(nèi)容(str)
antialias -> 是否平滑
color -> 計算機三原色(紅、綠占哟、藍),RGB顏色索烹,值的范圍都是0-255
(255,0,0) -> 紅色
(0,255,0) -> 綠色
(0,0,255) -> 藍色
(0,0,0) -> 黑色
(255,255,255) -> 白色
(X,X,X) -> 灰色
surface = font.render('你好, python', True, (0, 255, 0))
在python中沒有顯示中文的字體枫攀,如果要使用中文的顯示的話需要自己去下載字體文件ttf來添加
將內(nèi)容添加到窗口上
blit(需要顯示的對象, 顯示位置)
需要顯示的對象 --> Surface類型的數(shù)據(jù)
顯示位置 --> 坐標(x, y)
screen.blit(surface, (100, 100))
將窗口的內(nèi)容展示出來
pygame.display.flip()
2.在窗口內(nèi)添加圖片并顯示
獲取圖片對象
image = pygame.image.load('./images/luffy.jpeg')
同時也可以獲取圖片的大小
get_size()
image_size = image.get_size()
print(image_size)
對圖像進行形變
transform:形變包含縮放、旋轉(zhuǎn)和平移
scale(縮放對象,新的大小) --> 返回一個縮放后的新對象
image = pygame.transform.scale(image, (150, 150))
rotate(旋轉(zhuǎn)對象, 旋轉(zhuǎn)角度) --- 角度是0-360對應的度數(shù)
image = pygame.transform.rotate(image, -90)
rotozoom(形變的對象暇藏,角度橄抹,縮放的倍數(shù))--->旋轉(zhuǎn)縮放(等比例縮放靴迫,不會讓圖形變形)
image2=pygame.transform.rotozoom(image,0,0.4)
2.將圖片對象渲染到窗口上
screen.blit(image, (0, 0))
3.展示在屏幕上
pygame.display.flip()
畫圖形
1.畫直線
line(Surface, color, start_pos, end_pos, width=1)
Surface -> 畫在哪個地方
color -> 線的顏色
start_pos -> 起點
end_pos -> 終點
width -> 線的寬度
pygame.draw.line(screen, (255, 0, 0), (78, 59), (100, 100), 2)
pygame.draw.line(screen, (0, 255, 0), (0, 0), (130, 100), 2)
2.畫折線(可首尾相連,即起始點與終點相連)
lines(畫線的位置, 顏色, closed, 點的列表, width=1)
pygame.draw.lines(screen, (255, 0, 0), False, [(10, 50), (40, 80), (100, 200)], 5)
3.畫矩形
rect(位置楼誓,顏色玉锌,(x,y,width,height))
pygame.draw.rect(screen,(255,255,0),(0,0,200,200),2)
4.畫曲線
arc(Surface, color, Rect, start_angle, stop_angle, width=1)
Rect -> (x, y, width, height)矩形
start_angle
stop_angle
from math import pi
pygame.draw.arc(screen, (0, 0, 0), (0, 0, 100, 200), pi+pi/4, pi*2-pi/4)
5.畫圓
circle(位置, 顏色, 圓心位置, 半徑, width=0)
import random
pygame.draw.circle(screen,\
(random.randint(0,255),random.randint(0,255),random.randint(0,255)),\
(400,200),100)
6.畫橢圓
ellipse(Surface, color, Rect, width=0)
pygame.draw.ellipse(screen, (0, 100, 0), (100, 300, 200, 80), 1)
動畫原理
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255))
x = 0
y = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
x += 1
y += 1
screen.fill((255,255,255))
pygame.draw.circle(screen,(255,0,0),(x,y),80)
pygame.display.flip()