Pygame游戏入门

一.pygame的简介

pygame是跨平台Python模块,专为电子游戏设计。包含图像、声音。创建在SDL基础上,允许实时电子游戏研发而无需被低端语言,如C语言或是更低端的汇编语言束缚。基于这样一个设想,所有需要的游戏功能和理念都(主要是图像方面)完全简化位游戏逻辑本身,所有的资源结构都可以由高级语言提供,如Python。

二.pygame的安装

方式一:
在安装python并有网的情况下,打开cmd,输入pip install pygame命令即可自动下载安装pygame。
方式二:
可以去pygame官网http://www.pygame.org/download.shtml下载,也可以去下面下载地址: https://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame。根据自己所使用的操作系统版本和python版本 、不同安装选择下载文件,本人下载的文件及版本是pygame-1.9.6-cp36-cp36m-win32.whl。从cmd的命令提示符窗口中,进入pygame文件下载目录,输入安装命令: pip install pygame-1.9.6-cp36-cp36m-win32.whl

安装完成后,在cmd输入python -m pygame.examples.aliens命令即可打开pygame的一个内置游戏。

三.pygame的最小开发框架

Import pygame,sys
pygame.init()
screen = pygame.display.set_mode((600,400))
pygame.display.set_caption(“pygame游戏之旅”)
while True:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			sys.exit()
	pygame.display.update()

1.引入pygame和sys

import pygame,sys

sys是python的标准库
sys提供python运行时环境变量的操控
sys.exit()用于结束游戏并退出
2.初始化init()及设置

pygame.init()
screen = pygame.display.set_mode((600,400))
pygame.display.set_caption(“pygame游戏之旅”)

pygame.init()对pygame内部各功能模块进行初始化创建及变量设置,默认调用。
pygame.display.set_mode(size)初始化显示窗口,第一个参数size是一个二值元组,分别表示窗口的宽度和高度。
e.g.:设置窗口宽为600,高为400。
pygame.display.set_mode((600,400))或
size = width,height = 600,400
pygame.display.set_mode(size)
pygame.display.set_caption(“标题”)给窗口设置标题,显示在左上角位置。
3.获取事件并逐类响应

While True:
for event in pygame.event.get():
  	if event.type == pygame.QUIT:
  		sys.exit()

while True:无限循环,直到python运行时退出结束。
pygame.event.get()从pygame的事件队列中取出事件,并从
队列中删除该事件,例如:键盘按下是一个事件。
event.type获取事件类型,并逐类响应。
pygame.QUIT是pygame中定义的退出事件常量。
4.刷新屏幕

pygame.display.update()

pygame.display.update()对显示窗口进行更新,默认窗口全部重绘。与pygame.display.flip()的区别就是它可以局部更新。如果在括号里添加对象,则只更新括号里的那个对象。

四.pygame的模块概览

在这里插入图片描述

五.主要模块介绍

1.屏幕绘制
屏幕尺寸和模式
pygame.display.set_mode()设置相关屏幕模式
pygame.display.Info()生成屏幕相关信息、
窗口标题和图标
pygame.display.set_caption()设置标题信息
pygame.display.set_icon()设置图标信息
pygame.display.get_caption获得图标
窗口感知和刷新
pygame.display.get_active()
pygame.display.flip()
pygame.display.update()

pygame.display.Info()产生一个显示信息对象VideoInfo,表达当前屏幕的参数信息。如果在.set_mode()之前调用,则显示当前系统显示参数信息。参数很多,其中有两个十分重要,如下:current_w、current_h分别表示当前显示模式或窗口的像素宽度和高度。配合print()即可打印到控制台。
e.g.:print(pygame.display.Info())打印当前屏幕参数信息
print(pygame.display.Info().current_w)打印当前屏幕的宽
screen.get_width(),ball.get_height()获得该对象的宽、高等
pygame.VIDEORESIZE这是一种窗口大小更改的事件。事件发生后,返回event.size元组,包含新窗口的宽度和高度。event.size[0]为宽度,也可以用event.w;event.size[1]为高度,也可以用event.h。返回参数仅在事件发生时使用。
pygame.display.set_caption(title,icontitle=None) title设置窗口的标题内容,icontitle设置图标化后的小标题。小标题可选,部分系统没有。
pygame.display.get_caption()返回当前设置窗口的标题及小标题内容,返回结构为(title,icontitle)。该函数与游戏交互逻辑配合,可以根据游戏情节修改标题内容。
pygame.display.set_icon(surface)设置窗口的图标效果,图标是一个Surface对象。
e.g.:设置图标为PYG03-flower.png
icon = pygame.image.load(“PYG03-flower.png”)
pygame.display.set_icon(icon)
pygame.display.get_active()当窗口在系统中显示(屏幕绘制/非图标化)时返回True,否则返回False。该函数可以用来判断是 否游戏窗口被最小化。进一步,判断后可以暂停游戏,改变响 应模式等。
2.事件处理
pygame.event.EventType本质上是一种封装后的数据类型(对象)是pygame的一个类,表示事件类型。事件类型只有属性,没有方法。用户可自定义新的事件类型。
在这里插入图片描述
处理事件
pygame.event.get()
pygame.event.poll()
pygame.event.clear()
操作事件队列
pygame.event.set_blocked()
pygame.event.get.blocked()
pygame.event.set_allowed()
生成事件
pygame.event.post()
pygame.event.Event()

pygame.event.get()从事件队列中获得事件列表,即获得所有被队列的事件。遍历所有事件for event in pygame.event.get():。增加参数,获得某类或某些类事件:pygame.event.get(type)、pygame.event.get(typelist)。
pygame.event.poll()从事件队列中获得一个事件
while True:
event = pygame.poll()
事件获取将从事件队列中删除。如果事件队列为空,则返回event.NOEVENT。
pygame.event.clear()从事件队列中删除事件,默认删除所有事件。该函数与pygame.event.get()类似,区别仅是不对事件进行处理。可以增加参数,删除某类或某些类事件:pygame.event.clear(type)、pygame.event.clear(typelist)。
pygame.event.set_blocked(type or typelist)控制哪些类型事件不允许被保存到事件队列中。
pygame.event.set_allowed(type or typelist)控制哪些类型事件允许被保存到事件队列中。
pygame.event.get_blocked(type)测试某个事件类型是否被事件队列所禁止。如果事件类型被禁止,则返回True,否则返回False。
在这里插入图片描述
pgame.event.post(Event)产生一个事件,并将其放入事件队列。一般用于放置用户自定义事件(pygame.USEREVENT),也可以用于放置系统定义事件(如鼠标或键盘等),给定参数。
pygame.event.Event(type,dict)创建一个给定类型的事件。其中,事件的属性和值采用字典类型复制,属性名使用字符串形式。如果创建已有事件,属性需要一致。
pygame.event.KEYDOWN键盘按下事件。属性有event.unicode按键的unicode码;event.key按键的常量名称;event.mod按键修饰符的组合值。(注意:unicode码与平台有关,不推荐使用)
e.g.:在elif event.type == pygame.KEYDOWN:下输入
print(event.unicode,event.key,event.mod)>>s 115 0(按s)
pygame.event.KEYUP键盘释放事件。属性有event.key按键的常量名称;event.mod按键修饰符的组合值。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
event.mod修饰符的按位和运算
event.mod = KMOD_ALT | KMOD_SHIFT
在这里插入图片描述
pygame.event.MOUSEMOTION鼠标移动事件。属性有event.pos鼠标当前坐标值(x,y),相对于窗口左上角;event.rel鼠标相对运动距离(x,y),相对于上次事件;event.buttons鼠标按钮状态(a,b,c),对应于鼠标的三个键。鼠标移动时,这三个按键处于按下状态,对应的位置为1,反之则为0。
pygame.event.MOUSEBUTTONDOWN鼠标键按下事件。属性有event.pos鼠标当前坐标值(x,y),相对于窗口左上角;event.button鼠标按下键编号n。取值为整数,左键为1,右键为3,设备相关。
pygame.event.MOUSEBUTTONUP鼠标释放事件。属性有event.pos鼠标当前坐标值(x,y),相对于窗口左上角;event.button鼠标按下键编号n。取值0/1/2,分别对应三个键。
3.色彩与绘制
pygame.Color Color类用于表达色彩,使用RGB或RGBA色彩模式,A(透明度)可选。Color类可以使用色彩名字、RGBA值、HTML色彩格式等方式定义。例如:pygame.Color(“grey”)、pygme.Color(190,190,190,255)、pygame.Color(“#BEBEBEFF”)。
红绿蓝三个通道颜色组合,RGB取值范围0-255,整数。覆盖视力所能感知的所有颜色。Alpha通道表示不透明度,取值0-255,默认255。alpha通道值越大,不透明度越高,255表示不透明。
在这里插入图片描述
pygame.Color类
pygame.Color.r获得Color类的红色值r
pgame.Color.g获得Color类的绿色值g
pygame.Color.b获得Color类的蓝色值b
pygame.Color.a获得Color类的alpha值a
pygame.Color.normalize将RGBA各通道值归一到0-1之间
pygame.Rect表达一个矩形区域的类,用于存储坐标和长度信息。pygame利用Rect类来操作图形/图像等元素。Rect类提供了如下属性,返回一个数值或一个代表坐标的元组。X,y,w,h,size,width,height,top,left,bottom,right,topleft,bottomleft,topright,bottomright,midtop,midleft,midbottom,midright,center,centerx,centery。Rect类提供了如下方法,用来操作Rect类。.copy(),.move(),.inflate(),.clamp(),.clip(),.union(),.unionall(),.fit(),.normalize(),.contains(),.collidepoint(),.colliderect(),.collidelist(),.collidelistall(),.collidedict(),.collidedictall()。
e.g.: Rect1 = pygame.Rect(200,200,20,20) #虚拟一个Rect对象,括号里参数分别表示x,y,宽,高。
pygame.Rect.colliderect()检测两个 Rect 对象是否重叠,常用来解决碰撞问题。
e.g.: if Rect1.colliderect(birdRect): #判断Rect1是否和birdRect碰撞。
pygame.draw图形绘制后,返回一个矩形Rect类表示该形状。
方法有:.rect()矩形,.line()直线,.polygon()多边形,.lines()连续多线,.circle()圆形,.aaline()无锯齿线,.ellipse()椭圆形,.aalines()连续无锯齿线,.arc()椭圆弧形。
pygame.drawrect(Surface,color,Rect,width=0)绘制矩形。Surface矩形的绘制屏幕,Color矩形的绘制颜色,Rect矩形的绘制区域,width=0绘制边缘的宽度,默认为0,即填充图形。
e.g.:screen = pygame.display.set_mode((600,400))
GOLD = 255,251,0
r1rect = pygame.draw.rect(screen,GOLD,(100,100,200,100),5)
(100,100,200,100)分别代表x,y,长,宽
pygame.draw.polygons(Surface,color,pointlist,width=0)绘制多边形。Surface多边形的绘制屏幕,Color多边形的绘制颜色,pointlist多边形顶点坐标列表,width=0绘制边缘的宽度,默认为0,即填充图形。
pygame.draw.circle(Surface,color,pos,radius,width=0)绘制圆形。Surface圆形的绘制屏幕,Color圆形的绘制颜色,pos圆形的圆心坐标,radius圆形的半径,width=0绘制边缘的宽度,默认为0,即填充图形。
pygame.draw.ellipse(Surface,color,Rect,width=0)绘制椭圆形。Surface椭圆形的绘制屏幕,Color椭圆形的绘制颜色,Rect椭圆形的绘制区域,width=0绘制边缘的宽度,默认为0,即填充图形。
pygame.draw.arc(Surface,color,Rect,start_angle,stop_angle,width=0)绘制椭圆弧形。Surface椭圆弧形的绘制屏幕,Color椭圆弧形的绘制颜色,Rect椭圆弧形的绘制区域,start_angle,stop_angle弧形绘制起始和结束弧度值,横向右侧为0度,width=0绘制边缘的宽度,默认为0,即填充图形。
pygame.draw.line(Surface,color,start_pos,end_pos,width=1)绘制直线。Surface直线的绘制屏幕,Color直线的绘制颜色,start_pos,end_pos直线的起始和结束坐标,width=1直线的宽度,默认值为1.
pygame.draw.lines(Surface,color,closed,pointlist,width=1)绘制连续多线。Surface连续多线的绘制屏幕,Color连续多线的绘制颜色,closed如果为True,起止节点间自动增加封闭直线,pointlist连续多线的顶点坐标列表,width=1连续多线的宽度,默认值为1。
pygame.draw.alline(Surface,color,start_pos,end_pos,blend=1)绘制无锯齿线。Surface无锯齿线的绘制屏幕,Color无锯齿线的绘制颜色,start_pos,end_pos无锯齿线的起始和结束坐标,blend=1不为0时,与线条所在背景颜色进行混合。
pygame.draw.allines(Surface,color,closed,pointlist,blend=1)绘制连续无锯齿线。Surface连续无锯齿线的绘制屏幕,Color连续无锯齿线的绘制颜色,closed如果为True,起止节点间自动增加封闭直线,pointlist连续无锯齿线的顶点坐标列表,blend=1不为0时,与线条所在背景颜色进行混合。
使用系统字体绘制文字
pygame.font pygame中加载和表示字体的模块。
pygame.font.init()初始化字体
pygame.font.SysFont()从系统字体库创建一个 Font 对象
Font.render(text,False,fgcolor,bgcolor)>>Surface test绘制的文字内容,第二个参数为True或非0数为无锯齿,False或0为有锯齿,fgcolor,bgcolor字体颜色、背景颜色。
e.g.:在初始化位置添加
pygame.font.init()
f1 = pygame.font.SysFont(None,36) #None为系统默认字体,也可以设置其他系统字体,如”Arial”,字号为36
f1surf = f1.render(‘世界和平’,True,(255,251,0))
在屏幕刷新处添加
screen.blit(f1surf,(200,160))
使用自定义字体绘制文字
pygame.freetype向屏幕上绘制特定字体的文字。文字不能直接print(),而是用像素根据字体点阵图绘制。需额外引用:import pygame.freetype。
pygame.freetype.Font(file,size=0)根据字体和字号生成一个Font对象。File字体类型名称或路径,size字体的大小。用Font对象的render*方法绘制具体文字。
Font.render_to(sur,dest,text,fgcolor=None,bgcolor=None,rotation=0,size=0)>>Rect Font类的绘制方法1。surf绘制字体的平面,Surface对象,dest在平面中的具体位置(x,y),test绘制的文字内容,fgcolor文字颜色,bgcolor背景颜色,rotation逆时针的旋转角度,取值0-359,部分字体可旋转,size文字大小,赋值该参数将覆盖Font中的设定值。
e.g.:在初始化处添加
GOLD = 255,251,0
f1 = pygame.freetype.Font(“C://Windows//Fonts//msyh.ttc”,36)
f1rect = f1.render_to(screen,(200,160),”世界和平”,fgcolor=GOLD,size=50)
Font.render(text,fgcolor=None,bgcolor=None,rotation=0,size=0)>>Surface,Rect Font类的绘制方法2。test绘制的文字内容,fgcolor,bgcolor字体颜色、背景颜色,rotation逆时针的旋转角度,取值0-359,部分字体可旋转,size文字大小,赋值该参数将覆盖Font中的设定值。
e.g.: 在初始化处添加
GOLD = 255,251,0
f1 = pygame.freetype.Font(“C://Windows//Fonts//msyh.ttc”,36)
f1surf,f1rect = f1.render(“世界和平”,fgcolor=GOLD,size=50)
在屏幕刷新处添加
screen.blit(f1surf,(200,160))
windows系统的字体文件存放在C:\Windows\Fonts路径下。字体文件的扩展名为.ttf,.ttc。
4.其他
(1)填充背景图片
在刷新屏幕处添加
background = pygame.image.load(“路径”)(可写在初始化处)
screen.blit(background,(0,0)) (0,0)表示从坐标(0,0)开始填充
注意:screen.blit(background,(0,0))需写在刷新屏幕靠上处,如果写在其他screen.blit()或screen.fill(color)后面,则会将其覆盖。
(2)添加音频
pygame为我们提供了很便捷的方法来播放音频文件。这里分为两个方法:一个用来播放特效声音,一个用来播放背景音乐。
pygame.mixer.Sound(filename) filename:音频文件的文件名;
该方法返回一个Sound objects,调用他的.play( )方法,即可播放较短的音频文件(比如玩家受到伤害、收集到金币等)。
e.g.: scoreAudio = pygame.mixer.Sound(“score.wav”)
scoreAudio.play()
pygame.mixer.music.load(filename)filename:音频文件的文件名;该方法用来加载背景音乐,之后调用pygame.mixer.music.play( )方法就可以播放背景音乐(pygame 只允许加载一个背景音乐在同一个时刻),调用pygame.mixer.music.stop()方法停止播放背景音乐。
e.g.: pygame.mixer.music.load(‘welcome.ogg’) #加载背景音乐
pygame.mixer.music.play(-1, 0.0) #播放背景音乐,这里第一个参数为播放的次数(-1表示无限循环),第二个参数是设置播放的起点(单位为秒)

六.举例(壁球小游戏)

1.源程序
在这里插入图片描述
pygame.image.load(filename)将filename路径下的图像载入游戏,支持JPG、PNG、GIF(非动画)等13种常用图片格式。赋值后自动转为Surface对象,透明也可显示。
pygame.image.load(filename).convert()将图像转化为Surface对象,.convert()不加也可以,加了绘制速度更快。
pygame.image.load(filename).convert_alpha()相比convert,保留了Alpha 通道信息(可以简单理解为透明的部分),加载包含透明的图片时使用,普通图片也可使用。
ball.get_rect() pygame使用内部定义的Surface对象表示所有载入的图像,其中.get_rect()方法返回一个覆盖图像的矩形Rect对象。Rect对象有一些重要属性,例如top,bottom,left,right表示上下左右,width,height表示宽度、高度。
ballrect.move(x,y)矩形移动一个偏移量(x,y),即在横轴方向移动x像素,纵轴方向移动y像素,xy为整数。
screen.fill(color)显示窗口背景填充为color颜色,采用RGB色彩体系。由于壁球不断运动,运动后原有位置将默认填充白色,因此需要不断刷新背景色。
screen.bilt(src,dest)将一个图像绘制在另一个图像上,即将src绘制到dest位置上。通过Rect对象引导对壁球的绘制。
2.调整屏幕刷新率来调整小球速度
在初始化位置加

fps = 300
fclock = pygame.time.Clock()

在刷新屏幕位置加

fclock.tick(fps)

pygame.time.Clock()创建一个Clock对象,用于操作时间。
clock.tick(framerate)控制帧速度,即窗口刷新速度,例如:clock.tick(100)表示每秒钟100次帧刷新。视频中每次展示的静态图像称为帧。
3.添加方向键可控制小球速度
如下代码添加在事件处理处
在这里插入图片描述
pygame.KEYDOWN pygame对键盘敲击的事件定义,键盘每个键对应一个具体定义。
pygame.K_UPpygame.K_DOWNpygame.K_LEFTpygame.K_RIGHT分别对应方向上下左右键。
4.设置ESC键可退出游戏
在事件处理处elif event.type == pygame.KEYDOWN:下添加

if event.key == pygame.K_ESCAPE:
	sys.exit()

5.设置最小化后小球暂停运动
在刷新屏幕处加

if pygame.display.get_active():
	ballrect = ballrect.move(speed[0],speed[1])

6.设置背景颜色随小球的位置及速度而变化
在初始化位置添加

bgcolor = pygame.Color("red")
def RGBChannel(a):
	return 0 if a<0 else (255 if a>255 else int(a))

在刷新屏幕处添加

bgcolor.r = RGBChannel(ballrect.left/width*255)
bgcolor.g = RGBChannel(ballrect.top/width*255)
bgcolor.b = RGBChannel(min(speed[0],speed[1])/max(speed[0],speed[1],1)*255)
screen.fill(bgcolor)

7.设置屏幕信息
(1)设置为全屏
将screen = pygame.display.set_mode(screenSize)改为

screen = pygame.display.set_mode(screenSize,pygame.FULLSCREEN)

(2)设置为无边框
将screen = pygame.display.set_mode(screenSize)改为

screen = pygame.display.set_mode(screenSize,pygame.NOFRAME)

(3)设置为窗口大小随拖动更改
在事件处理处添加

elif event.type == pygame.VIDEORESIZE:
	screenSize = width,height = event.size[0],event.size[1]
	screen = pygame.display.set_mode(screenSize,pygame.RESIZABLE)

8.终极代码

import pygame,sys
pygame.init()
screenSize = width,height = 600,400
speed = [1,1]
fps = 300
fclock = pygame.time.Clock()
screen = pygame.display.set_mode(screenSize)
icon = pygame.image.load("PYG03-flower.png")
pygame.display.set_icon(icon)
pygame.display.set_caption("壁球游戏")
ball = pygame.image.load("PYG02-ball.gif")
ballrect = ball.get_rect()
bgcolor = pygame.Color("red")
def RGBChannel(a):
    return 0 if a<0 else (255 if a>255 else int(a))
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                speed[0] = speed[0] if speed[0] == 0 else (speed[0] - 1 if speed[0] > 0 else speed[0] + 1)     
            if event.key == pygame.K_RIGHT:
                speed[0] = speed[0] + 1 if speed[0] > 0 else speed[0] - 1
            if event.key == pygame.K_DOWN:
                speed[1] = speed[1] if speed[1] == 0 else (abs(speed[1])-1)*int(speed[1]/abs(speed[1]))
            if event.key == pygame.K_UP:
                speed[1] = speed[1] + 1 if speed[1] > 0 else speed[1] - 1
            if event.key == pygame.K_ESCAPE:
                sys.exit()
        elif event.type == pygame.VIDEORESIZE:
            screenSize = width,height = event.size[0],event.size[1]
            screen = pygame.display.set_mode(screenSize,pygame.RESIZABLE)
    if pygame.display.get_active():
        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]
    bgcolor.r = RGBChannel(ballrect.left/width*255)
    bgcolor.g = RGBChannel(ballrect.top/width*255)
    bgcolor.b = RGBChannel(min(speed[0],speed[1])/max(speed[0],speed[1],1)*255)
    screen.fill(bgcolor)
    screen.blit(ball,ballrect)
    pygame.display.update()
    fclock.tick(fps)

素材:
在这里插入图片描述PYG02-ball.gif
在这里插入图片描述PYG03-flower.png

发布了13 篇原创文章 · 获赞 18 · 访问量 4011

猜你喜欢

转载自blog.csdn.net/qq_19659617/article/details/104128171