一、
display——》屏幕相关
event——》事件
draw——》图形
image——》图片
font——》字体
import pygame #导入pygame模块
1、初始化游戏
pygame.init()
2、创建窗口
set.mode(size)——》size是元祖:(长,宽),单位是像素
fill(color)——》填充指定颜色,元祖(red,green,blue)
计算机使用的是计算机三原色(红、绿、蓝)——》RGB颜色(取值0-255)
red:(255,0,0)
green:(0,255,0)
blue:(0,0,255)
white:(255,255,255)
black:(0,0,0)
yellow:()
screen=pygame.display.set_mode((1080,720)) #窗口1080x720
screen.fill((255,255,255)) #填充颜色
3、显示图片
(1)加载图片
load(图片地址)——》返回图片对象
image=pygame.image.load('./file/image.jpg') #导入图片image
a、获取图片大小
图片.get_size()——》返回图片的大小,结果是元祖
image.get_size()
width,height=image.get_size()
b、对图片进行缩放
transform.scale(图片对象,大小)——》将指定的图片缩放成指定的大小,返回一个新的图片对象
注意:这种做法可能让图片发生形变
image1=pygame.transform.scale(image,(1080,720))
c、对图片进行缩放和旋转
transform.rotozoom(图片对象,角度,比例)
image2=pygame.transform.rotozoom(image,0,0.45)
(2)渲染图片
blit(渲染对象,渲染位置)
渲染位置——》元祖,(x坐标,y坐标)
screen.blit(image2,(0,0))
(3)画图(pygame.draw)
a、画线
def line(Surface,color,start_pos,end_pos,width=1)
surface:窗口,图片,文字对象
color_pos,end_pos:起点和终点(坐标)
width:线宽
================
def lines(Surface,color,close,pointlist,width=1)
close:是否连接终始点 True/False
pointlist:列表,列表中的元素是点对应的元祖
pygame.draw.line(screen,(255,0,0),(0,0),(200,200),3)
====================
points=[(23,45,),(100,570),(167,600),(450,600)]
pygame.draw.lines(screen,(0,255,23),True,points,2)
b、画圆
def circle(Surface, color, pos, radius, width=0)
pos:圆心坐标
radius:半径
pygame.draw.circle(screen,(123,43,54),(440,350),200,30)
c、def arc(Surface, color, Rect, start_angle, stop_angle, width=1)
rect:矩形,确认圆弧半径
start_angle:起始圆弧角
stop_angle:终点圆弧角
import pygame,math #需要导入数学模块 ,涉及 弧度值
pygame.draw.arc(screen,(12,43,5),((100,100),(100,200)),0,math.pi/0.5,2)
(4)展示内容(~~~~~~~~~~~~~~~~~)
要想将内容展示在屏幕上,都必须调用此方法
pygame.display.flip() #记住执行!!!!!!!!!
4、显示文字
(1)创建字体对象
SysFont(字体名,字体大小,是否加粗=False,是否倾斜=False)——》创建系统字体对象
Font(字体文件路径,字体大小)——》自定义字体
(2)根据字体创建文字对象
字体对象.render(文字,是否抗锯齿,颜色)
(3)在窗口上渲染文字
screen.blit(文字,大小)
font=pygame.font.SysFont('NewTimes',50) #系统文字,不能显示中文
font=pygame.font.Font('./file/aa.ttf',50) #自带文字,可显示中文
text=font.render('你好 python',True,(188,199,177))
screen.blit(text,(400,300))
pygame.display.flip()
5、游戏循环(不断检测是否有事件发生)
事件类型:event.type
鼠标事件
MOUSEBUTTONDOWN --> 鼠标按下
MOUSEBUTTONUP --> 鼠标弹起
MOUSEMOTION --> 鼠标移动
关心鼠标的位置:event.pos
键盘事件
KEYDOWN——》键盘按下
KEYUP——》键盘弹起
while True:
#不断检测事件的发生,只要有事件产生就会进入for循环
for event in pygame.event.get():
#不同类型的事件,event的type属性不同;
if event.type==pygame.QUIT:
exit()
elif event.type==pygame.MOUSEBUTTONDOWN:
#鼠标按下后要做的事就写在这儿
print('按下:双击666',event.pos)
pygame.draw.circle(screen, (23, 43, 54), event.pos, 30)
pygame.display.flip()# 记得更新,每步均需更新
elif event.type==pygame.MOUSEBUTTONUP:
# 鼠标松开后要做的事就写在这儿
print('松开:老铁!没毛病')
elif event.type == pygame.MOUSEMOTION:
# 鼠标移动要做的事就写在这儿
print('移动',event.pos)
elif event.type==pygame.KEYDOWN:
#键盘按下要做的事写下
print(event.key,chr(event.key))
elif event.type==pygame.KEYUP:
#键盘松开要做的事写下
print('放开我')