Python-Modules-pygame的学习记录

pygame简介

  • Pygame is a set of Python modules designed for writing video games.
  • Pygame adds functionality on top of the excellent SDL library.
  • This allows you to create fully featured games and multimedia programs in the python language.
  • pygame适用于游戏逻辑验证,游戏入门及系统演示验证;
  • pygame的官网请戳这里

pygame的最小开发框架

总共包含:引入、初始化、获取时间并逐类响应、刷新屏幕

import pygame # step1:引入pygame模块

pygame.init() # step2:初始化pygame的模块
screen = pygame.display.set_mode((400, 400)) # step2:初始化窗体<一个游戏有且仅有一个>
pygame.display.set_caption("pygame最小开发架构") # step2:设置这个基本窗体的标题
icon = pygame.image.load('player.png') # step2:初始化一些资源文件,音频视屏图片之类,返回surface对象
pygame.display.set_icon(icon) # step2:初始化设置icon图标
while True: # step3及step4的循环处理    
    for event in pygame.event.get(): # step3 轮询事件队列,并逐个给予处理
        if event.type == pygame.QUIT: # step3 对事件进行响应
            quit()

    pygame.display.update() #step4 刷新基本窗体,将变化体现在基本窗体上

一些相关的方法及对象

surface对象:又称为绘图层,图层对象;用于表示图片图形,文字图形或形状图形的绘制效果;

       多图层可以并列存在,在同一片rect中时会按照rect的先后顺序逐层覆盖;

       如果不在主图层中绘制的话,则不会显示;

rect对象:即矩形区域对象,其对应的是当前游戏主图层的某个矩形区域

              相当于主图层上某个矩形区域的指针或者标识信息;

      可以将指定的surface绘制到rect对象,即会在主图层的相关矩形区域内显示;

      rect的相关属性如下:

 

rect构造:
rect = pygame.Rect(left, top, width, height) # 构造方法1
rect = pygame.Rect((left, top), (width, height)) # 构造方法2
rect = pygame.Rect(surface_obj) # 构造方法3         
# 生成一个surface对象:
ball = pygame.image.loadl('dir') # 使用图片生成一个surface对象
black = pygame.Surface((10, 10)) # 直接生成一个surface对象

 pygame.time模块:
  pygame.time.get_ticks()  ——  获取以毫秒为单位的时间
  pygame.time.wait()  ——  暂停程序一段时间
  pygame.time.delay()  ——  暂停程序一段时间
  pygame.time.set_timer()  ——  在事件队列上重复创建一个事件
  pygame.time.Clock()  ——  创建一个对象来帮助跟踪时间

以下时间依赖于time.Clock()的对象:
    pygame.time.Clock.tick(fps)—这个方法应该在每个帧中调用一次。它将计算自上次调用以来已经传递了多少毫秒,使游戏整体帧数小于多少fps,不太精确,但是不怎么消耗cpu;
  pygame.time.Clock.tick_busy_loop(fps)—这个方法应该在每个帧中调用一次。它将计算自上次调用以来已经传递了多少毫秒,使游戏整体帧数小于多少fps,最精确,但会消耗过多的cpu;
  pygame.time.Clock.get_time—在前一个滴答声中使用的时间
  pygame.time.Clock.get_rawtime—在前一个滴答声中使用的实际时间
  pygame.time.Clock.get_fps—计算时钟帧速率

Pygame屏幕绘制机制

 pygame使用display模块来控制屏幕及显示,窗口只有一个,如果创建一个新的那么之前的将会被覆盖,一些详细的解释可以戳这个

    pygame.display.init()  —  初始化 display 模块
    pygame.display.quit()  —  结束 display 模块
    pygame.display.get_init()  —  如果 display 模块已经初始化,返回 True
    pygame.display.set_mode()  —  初始化一个准备显示的窗口或屏幕
    pygame.display.get_surface()  —  获取当前显示的 Surface 对象
    pygame.display.flip()  —  更新整个待显示的 Surface 对象到屏幕上
    pygame.display.update()  —  更新部分软件界面显示
    pygame.display.get_driver()  —  获取 Pygame 显示后端的名字
    pygame.display.Info()  —  创建有关显示界面的信息对象
    pygame.display.get_wm_info()  —  获取关于当前窗口系统的信息
    pygame.display.list_modes()  —  获取全屏模式下可使用的分辨率
    pygame.display.mode_ok()  —  为显示模式选择最合适的颜色深度
    pygame.display.gl_get_attribute()  —  获取当前显示界面 OpenGL 的属性值
    pygame.display.gl_set_attribute()  —  设置当前显示模式的 OpenGL 属性值
    pygame.display.get_active()  —  当前显示界面显示在屏幕上时返回 True
    pygame.display.iconify()  —  最小化显示的 Surface 对象
    pygame.display.toggle_fullscreen()  —  切换全屏模式和窗口模式
    pygame.display.set_gamma()  —  修改硬件显示的 gama 坡道
    pygame.display.set_gamma_ramp()  —  自定义修改硬件显示的 gama 坡道
    pygame.display.set_icon()  —  修改显示窗口的图标
    pygame.display.set_caption()  —  Set the current window caption
    pygame.display.get_caption()  —  Get the current window caption
    pygame.display.set_palette()  —  Set the display color palette for indexed displays
pygame.dispaly函数

 显示的窗口<screen>的尺寸及样式设置

screen = pygame.display.set_mode((400, 400), flags = 0) # 设置尺寸及样式
# size为一个长宽的元祖
# flags可以设置pygame.RESIZABLE<可调节大小> pygame.NOFRAME<设置无边框> pygame.FULLSCREEN<全屏>
# 设置相关的模式需要设定相关的处理机制
# 如时间pygame.VIDEORESIZE发生,则产生相应的操作,比如: # VIDEORESIZE时间表示窗体变更时间,返回event.size元祖<新窗体的长和宽>
 elif event.type == pygame.VIDEORESIZE:
    size = width, height = event.size[0], event.size[1] 
    screen = pygame.display.set_mode(size, flags=pygame.RESIZABLE)
# 在display.setmode()前获取屏幕尺寸
vInfo = pygame.display.Info() # 这时候获取的是屏幕的整体分辨率的对象,其有两个属性current_w及current_h可以用于全屏模式的设置

较常用的几个函数

pygame.display.get_active() # 显示当前屏幕的状态
pygame.display.flip() # 重新绘制整个窗口,当使用openGL硬件加速时,只能使用这个
pygame.display.update() # 只会绘制发生变化的区域至窗口
pygame.display.set_caption() # 设置显示窗体的标题
pygame.display.get_caption() # 获取显示窗体的标题
pygame.display.set_icon() # 设置显示窗体的图标

 Pygame的事件处理机制<基本内容>

Pygame handles all its event messaging through an event queue. The routines in this module help you manage that event queue.

The input queue is heavily dependent on the pygame.displaypygame module to control the display window and screen module.

The event subsystem should be called from the main thread.

The event queue has an upper limit on the number of events it can hold (128 for standard SDL 1.2).

When the queue becomes full new events are quietly dropped.

 event列表及返回值

# 系统事件
QUIT             none
ACTIVEEVENT      gain, state
# 键盘事件
KEYDOWN          unicode, key, mod
KEYUP            key, mod
# 鼠标事件
MOUSEMOTION      pos<当前的位置(X, Y)>, rel(相对移动), buttons<return(a, b, c)对应鼠标左、中、右键,按下为1,否则为0>
MOUSEBUTTONUP    pos<按下的位置>, button<哪个按键 1、2、3分别对应鼠标左、中、右键>
MOUSEBUTTONDOWN  pos<按下的位置>, button<哪个按键 1、2、3分别对应鼠标左、中、右键>
# 游戏操纵杆
JOYAXISMOTION    joy, axis, value
JOYBALLMOTION    joy, ball, rel
JOYHATMOTION     joy, hat, value
JOYBUTTONUP      joy, button
JOYBUTTONDOWN    joy, button
# 窗口事件
VIDEORESIZE      size, w, h
VIDEOEXPOSE      none
# 用户自定义
USEREVENT        code

事件的本质是一种封装的数据类型,是pygame种的一个类,这个类中只有属性没有方法,so用户也可以自定义event,如下:

import pygame, sys

pygame.init()
screen = pygame.display.set_mode((400, 500))
pygame.display.set_caption("Pygame事件自建")
fps = 1
fclock = pygame.time.Clock()
num = 1

while True:
    uevent = pygame.event.Event(pygame.USEREVENT, {'unicode':123, 'key':pygame.K_SPACE, 'mod':pygame.KMOD_ALT})
    # 自定义生成一个事件 (类型, 返回值) 类型也可以是event列表中的任意事件,返回值为一个字典
    pygame.event.post(uevent)
    # 并将这个事件加入事件队列中
    num = num+1
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.USEREVENT:
            if event.unicode == "":
                print("[USEREVENT {}]".format(num), "#", event.key, event.mod)
            else:
                print("[USEREVENT {}]".format(num), event.unicode, event.key, event.mod)
    pygame.display.update()
    fclock.tick(fps)

处理事件及事件队列的函数

pygame.event.pump—内部处理pygame事件处理程序
pygame.event.get—从队列中获取事件
pygame.event.poll—从队列中获取单个事件
pygame.event.wait—等待队列中的单个事件
pygame.event.peek—测试事件类型是否在队列中等待
pygame.event.clear—从队列中删除所有事件
pygame.event.event_name—从中获取字符串名称和事件ID
pygame.event.set_blocked—控制队列中允许哪些事件
pygame.event.set_allowed—控制队列中允许哪些事件
pygame.event.get_blocked —测试是否从队列中阻止了某种类型的事件
pygame.event.set_grab—控制与其他应用程序共享输入设备
pygame.event.get_grab—测试程序是否共享输入设备
pygame.event.post—在队列上放置一个新事件
pygame.event.Event —创建一个新的事件对象
pygame.event.EventType —用于表示SDL事件的pygame对象
pygame.event函数

较常用的几个函数

# 获取事件并处理的函数
pygame.event.get(type/typelist/空) 从队列中获取事件,获取到的所有消息并将其从队列中删除
pygame.event.poll() 从队列中获取单个事件
pygame.peek(type) peek(typelist) -> bool 如果队列中有这类型的事件则返回Trune
pygame.event.clear(type/typelist/空) 从队列中删除所有事件
# 操作时间队列的函数
pygame.event.set_blocked(type/typelist/空) 控制队列中允许哪些事件
pygame.event.set_allowed((type/typelist/空) 控制队列中允许哪些事件
pygame.event.get_blocked(type) 测试是否从队列中阻止了某种类型的事件
# 生成事件的函数
pygame.event.post(Event) 在队列上放置一个新事件
pygame.event.Event(type, dict/**attributes) 创建一个新的事件对象
# 属性
pygame.event.EventType 用于表示SDL事件的pygame对象
pygame.event.EventType.type—SDL事件类型标识符,int类型
pygame.event.EventType .__ dict__ —事件对象属性字典
# 其他
pygame.event.set_grab(bool) - >None控制与其他应用程序共享输入设备
pygame.event.get_grab() -> bool 是否控制与其他应用程序共享输入设备

 pygame色彩与绘图

The Color class represents RGBA color values using a value range of 0 to 255 inclusive.

 pygame.Color色彩

pygame.Color.r—得到或设置颜色的红色值
pygame.Color.g—得到或设置颜色的绿色值
pygame.Color.b—得到或设置颜色的蓝色值
pygame.Color.a—得到或设置颜色的透明度
pygame.Color.cmy—获取或设置cmy表示颜色
pygame.Color.hsva—获取或设置hsva表示的颜色
pygame.Color.hsla—获取或设置hsla表示颜色
pygame.Color.i1i2i3—获取或设置i1i2i3表示颜色
pygame.Color.normalize—返回规范化的RGBA值
pygame.Color.correct_gamma—对颜色应用一个特定的伽马值
pygame.Color.set_length—将颜色的元素设置为1,2,3或4
pygame.Color.fun

常用的方法

# 创建Color对象
GREEN = pygame.Color('green') 使用色彩名称直接创建
WHITE = pygame.Color(255, 255, 255, 255) 使用4元组创建,分别对应red、green、bule 、alpha 即,红绿蓝即透明度
# 常用的一些颜色组合
白(255,255,255)    黑(0,0,0)    灰(190,190,190)    紫色(160,32,240)
深绿绿(0,100,0)    金(255,215,0) 紫罗兰(238,130,238# 获取一些属性
Color.r Color.g Color.b Color.a 分别获取红绿蓝即透明度
Color.normalize(0-1) 将0-255变成对应的0-1间的浮点数用于API之类的

pygame.draw绘图

Draw several simple shapes to a surface. These functions will work for rendering to any format of surface.
pygame.draw.rect:    绘制矩形
pygame.draw.polygon:  绘制任意边数的多边形
pygame.draw.circle:  绘制圆
pygame.draw.ellipse:  在矩形内绘制椭圆
pygame.draw.arc:     绘制圆弧(或者椭圆的一部分)
pygame.draw.line:    绘制直线(线段)
pygame.draw.lines:  从一个点列表中连续绘制直线段
pygame.draw.aaline:  绘制一根平滑的线(反锯齿)
pygame.draw.aalines:  绘制一系列平滑的线
pygame.draw.fun

以上的函数具体参数信息,如需了解戳这里,下面是个简单的例子

import pygame
from math import pi

pygame.init() # 窗体初始化

size = width, height = 800, 600
screen = pygame.display.set_mode(size)
pygame.display.set_caption("键盘输入测试")

# 定义色彩的集中方式
GOLD = 255, 251, 0
RED = pygame.Color('red')
WHITE = 255, 255, 255
GREEN = pygame.Color('green')
# 绘制各种简单的图形
e1rect = pygame.draw.ellipse(screen, GREEN, (50,50,500,300), 3)
c1rect = pygame.draw.circle(screen, GOLD, (200,180), 30, 5)
c2rect = pygame.draw.circle(screen, GOLD, (400,180), 30)
r1rect = pygame.draw.rect(screen, RED, (170, 130, 60, 10), 3)
r2rect = pygame.draw.rect(screen, RED, (370, 130, 60, 10))
plist = [(295, 170), (285, 250), (260, 280), (340, 280), (315, 250), (305, 170)]
l1rect = pygame.draw.lines(screen, GOLD, True, plist, 2)
a1rect = pygame.draw.arc(screen, RED, (200, 220, 200, 100), 1.4*pi, 1.9*pi, 3)

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

    pygame.display.update()

pygame.freestype字体绘制模块

pygame.freetype模块是pygame.font模块的替代品,用于加载和呈现字体。它具有原始的所有功能,以及许多新功能。

它绝对不依赖于SDL_ttf库。它直接在FreeType 2库上实现。

pygame.freetype模块本身不与pygame.font模块向后兼容;相反,使用pygame.ftfont模块作为pygame.font模块的替代品。

支持TTF,Type1,CFF,OpenType,SFNT,PCF,FNT,BDF,PFR和Type42字体

pygame.freestype需要额外的引用

pygame.freetype.get_error - 返回最新的FreeType错误
pygame.freetype.get_version - 返回FreeType版本
pygame.freetype.init - 初始化基础FreeType库。
pygame.freetype.quit - 关闭底层的FreeType库。
pygame.freetype.was_init - 返回是否初始化FreeType库。
pygame.freetype.get_cache_size - 返回字形大小
pygame.freetype.get_default_resolution - 以每英寸点数返回默认像素大小
pygame.freetype.set_default_resolution - 为模块设置默认像素大小,以每英寸点数为单位
pygame.freetype.SysFont - 从系统字体创建一个Font对象
pygame.freetype.get_default_font - 获取默认字体的文件名
pygame.freetype.Font - 从支持的字体文件创建一个新的Font实例。
pygame.freestype.fun

常用函数,其他内容参考戳这里

# 生成字体对象并调用
将渲染文本作为surface返回
render(text, fgcolor=None, bgcolor=None, style=STYLE_DEFAULT, rotation=0, size=0) -> (Surface, Rect)
将文本渲染到现有surface上
render_to(surf, dest, text, fgcolor=None, bgcolor=None, style=STYLE_DEFAULT, rotation=0, size=0) -> Rect
#例子如下:
font1 = pygame.freetype.Font("C:\Windows\Fonts\Arrus.ttc", 36)
f1rect = font1.render_to(screen, (200, 100), "你好啊世界!", fgcolor=GOLD, size=50)
f1screen, f1rect = font1.render("Hello World!!", fgcolor=GOLD, size=50)

绘图的原理及精髓

pygame.Surface (绘图层,或绘图平面,或图层)

   用于表示图形、文字或图像的绘制效果,与当前屏幕主图层可以并列存在,不绘制在主图层上不会显示;

pygame.Rect (矩形区域)

  对应当前主图层的某个具体区域,相当于某个矩形区域的指针或标识信息,可以指定图层绘制在某个矩形区域中;

主图层:

  由pygame.display.set_mode()生成的Surface对象即主图层,可以被屏幕直接显示的;

  在主图层上绘制其他图层使用.blit()方法,将pygame.Surface --绘制-> pygame.Rect

# 使用图像生成Surface对象
planeImg = pygame.image.load(get_source_dir('player.png'))
# 生成一个rect对象
myRect = pygame.Rect((0, 0), (64, 64)) 
# 生成主图层
screen = pygame.display.set_mode((400, 400))
# 将surface绘制到主图层
screen.blit(planeImg, myRect)

      

   

 

end

原文地址:https://www.cnblogs.com/FcBlogPythonLinux/p/12316447.html