Pygame色彩与绘图机制-慕课的python游戏开发入门03

目录

一、Pygame色彩机制

 (1)四种表达方式

(2)RGB色彩模式

(3)RGBA色彩模式

(4)pygame.Color类

二、Pygame图形绘制机制

(1)图形绘制

 <1>pygame.draw.rect(Surface, color, Rect, width=0)

<2>pygame.draw.polygon(Surface, color, pointlist, width=0)

<3>pygame.draw.circle(Surface, color, pos, radius, width=0)

扫描二维码关注公众号,回复: 15555074 查看本文章

<4>pygame.draw.ellipse(Surface, color, Rect, width=0)

<5>pygame.draw.arc(Surface, color, Rect, start_angle,stop_angle, width=0)

<6>pygame.draw.line(Surface, color, start_pos, end_pos, width=1)

<7>pygame.draw.lines(Surface, color, closed, pointlist, width=1)

<8>pygame.draw.aaline(Surface, color, start_pos, end_pos, blend=1)

<9>pygame.draw.aalines(Surface, color, closed, pointlist, blend=1)

(2)文字绘制

<1>引用

<2>系统中的字体

<3>生成font对象

<4>绘制具体文字

(3)Rect类

<1>Rect类属性

<2>Rect类方法

(4)绘图机制的精髓

<1>理解Pygame的两个重要类型

<2>主图层

三、代码分析

1、小球游戏,背景随着运动变化,演示RGB颜色变化

2、演示图形绘制

3、演示文字绘制

4、演示文字的操作

四、小结


本文介绍pygame的色彩机制和绘图机制,是如何实现在游戏内实现丰富的色彩和图形呈现,实现游戏的多彩丰富性。

一、Pygame色彩机制

 (1)四种表达方式

Color类用于表达色彩,使用RGB或RGBA色彩模式,A可选
Color类可以用色彩名字、 RGBA值、 HTML色彩格式等方式定义

例如:
Color(name) 例如:Color("grey")
Color(r,g,b,a) 例如:Color(190, 190, 190, 255)
Color(rgbvalue) 例如:Color("#BEBEBEFF")

(2)RGB色彩模式

英文名称        R.G.B.         中文名称
white         255 255 255         白色
black         0 0 0                     黑色
grey 1        90 190 190         灰色
darkgreen         0 100 0         深绿色
gold         255 215 0                 金色
violet         238 130 238         紫罗兰
purple         160 32 240         紫色

(3)RGBA色彩模式

• RGB色彩模式之外增加了第四维度:alpha通道
• alpha通道表示不透明度,取值0-255,默认255
• alpha通道值越大,不透明度越高,255表示不透明

(4)pygame.Color类

pygame.Color.r 获得Color类的红色值r
pygame.Color.g 获得Color类的绿色值g
pygame.Color.b 获得Color类的蓝色值b
pygame.Color.a 获得Color类的不透明度值a
pygame.Color.normalize 将RGBA各通道值归一到0-1之间


二、Pygame图形绘制机制

(1)图形绘制

pygame.draw

向屏幕上绘制一些简单的图形,如直线、圆形、椭圆等。任何一个图形绘制后,会返回一个矩形Rect类表示该形状

 <1>pygame.draw.rect(Surface, color, Rect, width=0)

• Surface 矩形的绘制屏幕
• color 矩形的绘制颜色
• Rect 矩形的绘制区域
• width=0 绘制边缘的宽度,默认为0,即填充图形

<2>pygame.draw.polygon(Surface, color, pointlist, width=0)

• Surface 多边形的绘制屏幕
• color 多边形的绘制颜色
• pointlist多边形顶点坐标列表
• width=0 绘制边缘的宽度,默认为0,即填充图形

<3>pygame.draw.circle(Surface, color, pos, radius, width=0)

• Surface 圆形的绘制屏幕
• color 圆形的绘制颜色
• pos 圆形的圆心坐标
• radius 圆形的半径
• width=0 绘制边缘的宽度,默认为0,即填充图形

<4>pygame.draw.ellipse(Surface, color, Rect, width=0)

• Surface 椭圆形的绘制屏幕
• Color 椭圆形的绘制颜色
• Rect 椭圆形的绘制区域
• width=0 绘制边缘的宽度,默认为0,即填充图形

<5>pygame.draw.arc(Surface, color, Rect, start_angle,stop_angle, width=0)

Surface 椭圆弧形的绘制屏幕
Color 椭圆弧形的绘制颜色
Rect 椭圆弧形的绘制区域
start_angle, stop_angle 弧形绘制起始和结束弧度值
width=0 绘制边缘的宽度,默认为0,即填充图形

<6>pygame.draw.line(Surface, color, start_pos, end_pos, width=1)

• Surface 直线的绘制屏幕
• Color 直线的绘制颜色
• start_pos, end_pos 直线的起始和结束坐标
• width=1 直线的宽度,默认值为1

<7>pygame.draw.lines(Surface, color, closed, pointlist, width=1)

• Surface 连续多线的绘制屏幕
• Color 连续多线的绘制颜色
• closed 如果为True,起止节点间自动增加封闭直线
• pointlist连续多线的顶点坐标列表
• width=1 连续多线的宽度,默认值为1

<8>pygame.draw.aaline(Surface, color, start_pos, end_pos, blend=1)

• Surface 无锯齿线的绘制屏幕
• Color 无锯齿线的绘制颜色
• start_pos, end_pos 无锯齿线的起始和结束坐标
• blend=1 不为0时,与线条所在背景颜色进行混合

<9>pygame.draw.aalines(Surface, color, closed, pointlist, blend=1)

• Surface 连续无锯齿线的绘制屏幕
• Color 连续无锯齿线的绘制颜色
• closed 如果为True,起止节点间自动增加封闭直线
• pointlist连续无锯齿线的顶点坐标列表
• blend=1 不为0时,与线条所在背景颜色进行混合

(2)文字绘制

pygame.freetype

<1>引用

pygame.freetype是绘制文字的增强方法,建议使用
必须额外增加import引用,如下:
import pygame,sys
import pygame.freetype

<2>系统中的字体

Windows系统
C:\Windows\Fonts
字体文件的扩展名
*.ttf *.ttc

<3>生成font对象

pygame.freetype.Font 根据字体和字号生成一个Font对象

Font类
pygame.freetype.Font(file, size=0)

• file 字体类型名称或路径
• size 字体的大小
 

<4>绘制具体文字

①Font.render_to()方法

Font.render_to(surf, dest, text, fgcolor=None,bgcolor=None, rotation=0, size=0) —> Rect

• surf 绘制字体的平面,Surface对象
• dest 在平面中的具体位置,(x,y)
• text 绘制的文字内容
• fgcolor 文字颜色

• bgcolor 背景颜色
• rotation 逆时针的旋转角度,取值0-359,部分字体可旋转
• size 文字大小,赋值该参数将覆盖Font中的设定值

Rect 返回一个Rect对象

②Font.render()方法

Font.render(text, fgcolor=None, bgcolor=None,rotation=0, size=0) —> (Surface, Rect)

• text 绘制的文字内容
• fgcolor, bgcolor 字体颜色、背景颜色
• rotation 逆时针的旋转角度,取值0-359,部分字体可旋转
• size 文字大小,赋值该参数将覆盖Font中的设定值

返回一个元组,包含Surface对象和Rect对象

(3)Rect类

pygame.Rect

表达一个矩形区域的类,用于存储坐标和长度信息。Pygame利用Rect类来操作图形/图像等元素

四个参数:
left, top, width, height

<1>Rect类属性

Rect类提供了如下属性,返回一个数值或一个代表坐标的元组
x, y, w, h, size, width, height,top, left, bottom, right,topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright,center, centerx, centery,(left,top),

<2>Rect类方法

Rect类提供了如下方法,用来操作Rect类
.copy(), .move(), .inflate(), .clamp(), .clip(),.union(), .unionall(), .fit(),.normalize(), .contains(), .collidepoint().colliderect(), .collidelist(), .collidelistall(),.collidedict(), .collidedictall()

(4)绘图机制的精髓

<1>理解Pygame的两个重要类型

①pygame.Surface:
绘图层,或绘图平面,或图层
• 用于表示图形、文字或图像的绘制效果
• 与当前屏幕主图层可以并列存在
• 如果不绘制在主图层上,则不会被显示
②pygame.Rect

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

<2>主图层

由pygame.display.set_mode()生成的Surface对象
例如:

size = width, height = 600, 400
screen = pygame.display.set_mode(size)

在主图层上绘制其他图层使用.blit()方法
screen.blit(ball, ballrect)
其中ball是pygame.Surface,而ballrect是 pygame.Rect
Rect绘制到Surface中,然后绑定到主图层上后显示

三、代码分析

1、小球游戏,背景随着运动变化,演示RGB颜色变化

# Unit PYG05: Pygame Wall Ball Game Version 9
import pygame, sys

pygame.init()
icon = pygame.image.load("PYG03-flower.png")
pygame.display.set_icon(icon)
size = width, height = 600, 400
speed = [1,1]
BLACK = 0, 0, 0
screen = pygame.display.set_mode(size, pygame.RESIZABLE)
pygame.display.set_caption("Pygame壁球")
ball = pygame.image.load("PYG02-ball.gif")
ballrect = ball.get_rect()
fps = 300
fclock = pygame.time.Clock()
still = False
bgcolor = pygame.Color("black")

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 (abs(speed[0]) - 1)* int(speed[0]/abs(speed[0]))
            elif event.key == pygame.K_RIGHT:
                speed[0] = speed[0] + 1 if speed[0] > 0 else speed[0] - 1
            elif event.key == pygame.K_UP:
                speed[1] = speed[1] + 1 if speed[1] > 0 else speed[1] - 1
            elif event.key == pygame.K_DOWN:
                speed[1] = speed[1] if speed[1] == 0 else (abs(speed[1]) - 1) * int(speed[1] / abs(speed[1]))
            elif event.key == pygame.K_ESCAPE:
                sys.exit()
        elif event.type == pygame.VIDEORESIZE:
            size = width, height = event.size[0], event.size[1]
            screen = pygame.display.set_mode(size, pygame.RESIZABLE)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                still = True
        elif event.type == pygame.MOUSEBUTTONUP:
            still = False
            if event.button == 1:
                ballrect = ballrect.move(event.pos[0] - ballrect.left, event.pos[1] - ballrect.top)
        elif event.type == pygame.MOUSEMOTION:
            if event.buttons[0] == 1:
                ballrect = ballrect.move(event.pos[0] - ballrect.left, event.pos[1] - ballrect.top)
    if pygame.display.get_active() and not still:
        ballrect = ballrect.move(speed[0], speed[1])
    if ballrect.left < 0  or ballrect.right >width:
        speed[0] = - speed[0]
        if ballrect.right > width and ballrect.right + speed[0] > ballrect.right:
            speed[0] = - speed[0]
    if ballrect.top < 0  or ballrect.bottom > height:
        speed[1] = - speed[1]
        if ballrect.bottom > height and ballrect.bottom + speed[1] > ballrect.bottom:
            speed[1] = - speed[1]

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

    screen.fill(bgcolor)
    screen.blit(ball,ballrect)
    pygame.display.update()
    fclock.tick(fps)

代码说明:

def RGBChannel(a):     

        return 0 if a<0 else (255 if a>255 else int(a))

定义函数,如果输入值大于255或者小于0则返回0,如果的0-255之间则返回值,将RGB的参数控制在0-255中。

bgcolor.r = RGBChannel(ballrect.left*255/width)

bgcolor.g = RGBChannel(ballrect.top*255/height)

bgcolor.b = RGBChannel(min(speed[0],speed[1])*255/max(speed[0],speed[1],1))

R:水平距离/窗体宽度,取值0-255
G:垂直距离/窗体高度,取值0-255
B:最小速度/最大速度,取值0-255

screen.fill(bgcolor)

用生成背景色填充

2、演示图形绘制

# Unit PYG05: Pygame Shape Draw Test
import pygame, sys
from math import pi

pygame.init()
screen = pygame.display.set_mode((600,400))
pygame.display.set_caption("Pygame图形绘制")
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:
            sys.exit()
    pygame.display.update()

代码解析:

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)

分别绘制不同的图形

3、演示文字绘制

import pygame, sys
import pygame.freetype

pygame.init()
screen = pygame.display.set_mode((600,400))
pygame.display.set_caption("Pygame文字绘制")
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)

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

代码分析:

f1 = pygame.freetype.Font("C://Windows//Fonts//msyh.ttc", 36)

生成一个font对象

f1rect = f1.render_to(screen, (200,160), "世界和平", fgcolor=GOLD, size=50)

用render_to 方法生成文字并显示到screen上

返回一个Rect对象,可以操纵

import pygame, sys
import pygame.freetype

pygame.init()
screen = pygame.display.set_mode((600,400))
pygame.display.set_caption("Pygame文字绘制")
GOLD = 255, 251, 0

f1 = pygame.freetype.Font("C://Windows//Fonts//msyh.ttc", 36)
f1surf, f1rect = f1.render("世界和平", fgcolor=GOLD, size=50)

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

    screen.blit(f1surf, (200,160))
    pygame.display.update()

本例采用render的方法,返回一个Surface对象和一个rect对象,需要后来绑定到主图层上screen.blit(f1surf, (200,160))

4、演示文字的操作

import pygame, sys
import pygame.freetype

pygame.init()
size = width, height = 600, 400
speed = [1,1]
GOLD = 255, 251, 0
BLACK = 0, 0, 0
pos = [230, 160]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pygame文字绘制")
f1 = pygame.freetype.Font("C://Windows//Fonts//msyh.ttc", 36)
f1surf, f1rect = f1.render("世界和平", fgcolor=GOLD, size=50)
fps = 300
fclock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    if pos[0] < 0 or pos[0] + f1rect.width > width:
        speed[0] = - speed[0]
    if pos[1] <0 or pos[1] + f1rect.height > height:
        speed[1] = - speed[1]
    pos[0] = pos[0] + speed[0]
    pos[1] = pos[1] + speed[1]

    screen.fill(BLACK)
    f1surf, f1rect = f1.render("世界和平", fgcolor=GOLD, size=50)
    screen.blit(f1surf, (pos[0], pos[1]))
    pygame.display.update()
    fclock.tick(fps)

screen.blit(f1surf, (pos[0], pos[1])),通过变换绑定文字位置的变化,实现小球一样的一个文字。

四、小结

1、正确认识Surface对象和Rect对象的应用,游戏内元素的操作实际都是通过Rect的操作完成,而显示到游戏画面上则需要借助Surface对象,surface对象可以生成后不显示,什么时候显示绑定到主图层上即可。

2、颜色机制的四种表达方式,选择适合自己的,建议采用使用RGB或RGBA色彩模式,至于rgb的值,反正我是记不住,用的时候查一下就行了。

3、颜色的变化可以通过操纵pygame.Color类进行,RGB量值的变化,从而形成颜色的变化

4、图形的绘制生成Rect对象,可以通过操作Rect对象来操作

5、pygame.freetype是其中的一种文字绘制的方法,要搞清楚render_to 和render方法的不同之处。

结语:

慕课python游戏开发入门的主要内容就是这些,内容十分基础,不愧称之为入门教程,内容十分的基础,甚至于没有涉到pygame的灵魂-Sprite精灵和Group组。因此还需要进一步学习。

猜你喜欢

转载自blog.csdn.net/sygoodman/article/details/124358891