Pygame color and drawing mechanism - Introduction to Python game development of MOOC 03

Table of contents

1. Pygame color mechanism

 (1) Four ways of expression

(2) RGB color mode

(3) RGBA color mode

(4) pygame.Color class

Two, Pygame graphics drawing mechanism

(1) Graphic drawing

 <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)

<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) Text drawing

<1> Quote

<2> Fonts in the system

<3> Generate font object

<4> Draw specific text

(3) Rect class

<1>Rect class attribute

<2> Rect class method

(4) The essence of the drawing mechanism

<1> Understand the two important types of Pygame

<2>Main layer

3. Code Analysis

1. The ball game, the background changes with the movement, and the RGB color change is demonstrated

2. Demonstration graphics drawing

3. Demo text drawing

4. Demonstration text operation

Four. Summary


This article introduces the color mechanism and drawing mechanism of pygame, how to achieve rich color and graphic presentation in the game, and realize the colorful richness of the game.

1. Pygame color mechanism

 (1) Four ways of expression

Color class is used to express color, use RGB or RGBA color mode, A optional
Color class can be defined by color name, RGBA value, HTML color format, etc.

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

(2) RGB color mode

English name RGB Chinese name
white 255 255 255 white
black 0 0 0 black
gray 1 90 190 190 gray
darkgreen 0 100 0 dark green
gold 255 215 0 golden
violet 238 130 238 violet
purple 160 32 240 purple

(3) RGBA color mode

• A fourth dimension is added besides the RGB color mode: alpha channel
• The alpha channel represents opacity, the value is 0-255, and the default is 255
• The larger the value of the alpha channel, the higher the opacity, and 255 represents opacity

(4) pygame.Color class

pygame.Color.r Get the red value r of the Color class
pygame.Color.g Get the green value g of the Color class
pygame.Color.b Get the blue value b of the Color class
pygame.Color.a Get the opacity value a of the Color class
pygame.Color.normalize normalizes each channel value of RGBA to between 0-1


Two, Pygame graphics drawing mechanism

(1) Graphic drawing

pygame.draw

Draw some simple graphics on the screen, such as straight lines, circles, ellipses, etc. After any graphic is drawn, a rectangle Rect class will be returned to represent the shape

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

• Surface rectangle drawing screen
• color rectangle drawing color
• Rect rectangle drawing area
• width=0 drawing edge width, the default is 0, that is, filling graphics

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

• Surface polygon drawing screen
• color polygon drawing color
• pointlist polygon vertex coordinates list
• width=0 draw edge width, the default is 0, that is to fill the graph

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

• Surface the drawing screen of the circle
• color the drawing color of the circle
• pos the coordinates of the center of the circle
• radius the radius of the circle
• width=0 the width of the drawing edge, the default is 0, that is, filling the graphics

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

• Surface ellipse drawing screen
• Color ellipse drawing color
• Rect ellipse drawing area
• width=0 draw edge width, the default is 0, that is to fill the graphics

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

Surface The drawing screen of the ellipse arc
Color The drawing color of the ellipse arc
Rect The drawing area of ​​the ellipse arc
start_angle, stop_angle The starting and ending arc value of the arc drawing
width=0 The width of the drawing edge, the default is 0, that is, filling the graph

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

• Surface the drawing screen of the line
• Color the drawing color of the line
• start_pos, end_pos the start and end coordinates of the line
• width=1 the width of the line, the default value is 1

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

• Surface drawing screen of continuous multi-lines
• Color drawing color of continuous multi-lines
• closed If it is True, a closed line is automatically added between the start and end nodes
• pointlist list of vertex coordinates of continuous multi-lines
• width=1 width of continuous multi-lines, the default value is 1

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

• Surface is the drawing screen of the jagged line
• Color is the drawing color of the jagged line
• start_pos, end_pos is the start and end coordinates of the jagged line
• blend=1 When it is not 0, blend with the background color of the line

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

• Surface is the drawing screen of continuous non-jaggy lines
• Color is the drawing color of continuous non-jaggy lines
•closed If it is True, a closed line is automatically added between the start and end nodes
•pointlist is the vertex coordinate list of continuous non-jaggy lines
•blend=1 When it is not 0, Blend with the background color of the line

(2) Text drawing

pygame.freetype

<1> Quote

pygame.freetype is an enhanced method for drawing text. It is recommended to use
additional import references, as follows:
import pygame,sys
import pygame.freetype

<2> Fonts in the system

Windows system
C:\Windows\Fonts
font file extension
*.ttf *.ttc

<3> Generate font object

pygame.freetype.Font generates a Font object based on font and font size

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

• file font type name or path
• size font size
 

<4> Draw specific text

①Font.render_to() method

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

• surf The plane on which the font is drawn, Surface object
• dest The specific position in the plane, (x,y)
• text The content of the drawn text
• fgcolor Text color

• bgcolor background color
• rotation counterclockwise rotation angle, value 0-359, some fonts can be rotated
• size text size, assigning this parameter will overwrite the setting value in Font

Rect returns a Rect object

②Font.render() method

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

• text The content of the drawn text
• fgcolor, bgcolor font color, background color
• rotation counterclockwise rotation angle, value 0-359, some fonts can be rotated
• size text size, assigning this parameter will override the setting value in Font

Returns a tuple containing Surface objects and Rect objects

(3) Rect class

pygame.Rect

A class representing a rectangular area, used to store coordinate and length information. Pygame uses the Rect class to manipulate elements such as graphics/images

Four parameters:
left, top, width, height

<1>Rect class attribute

The Rect class provides the following properties, returning a value or a tuple representing coordinates
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 class method

The Rect class provides the following methods for manipulating the Rect class
.copy(), .move(), .inflate(), .clamp(), .clip(), .union(), .unionall(), .fit( ), .normalize(), .contains(), .collidepoint(), .colliderect(), .collidelist(), .collidelistall(), .collidedict(), .collidedictall()

(4) The essence of the drawing mechanism

<1> Understand the two important types of Pygame

①pygame.Surface:
Drawing layer, or drawing plane, or layer
• It is used to represent the drawing effect of graphics, text or images
• It can exist side by side with the main layer of the current screen
• If it is not drawn on the main layer, it will not be drawn display
②pygame.Rect

Rectangular area
• Corresponds to a specific area of ​​the current main layer
• Equivalent to a pointer or identification information of a rectangular area
• Can specify a layer to be drawn in a rectangular area

<2>Main layer

Surface objects generated by pygame.display.set_mode()
For example:

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

To draw other layers on the main layer, use the .blit() method
screen.blit(ball, ballrect)
where ball is pygame.Surface, and ballrect is pygame.Rect
Rect is drawn into Surface and then bound to the main layer after display

3. Code Analysis

1. The ball game, the background changes with the movement, and the RGB color change is demonstrated

# 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)

Code description:

def RGBChannel(a):     

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

Define a function that returns 0 if the input value is greater than 255 or less than 0, and returns a value if the input value is between 0-255, and controls the RGB parameters within 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: horizontal distance/window width, value 0-255
G: vertical distance/window height, value 0-255
B: minimum speed/maximum speed, value 0-255

screen.fill(bgcolor)

Fill with generated background color

2. Demonstration graphics drawing

# 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()

Code analysis:

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)

Draw different graphics separately

3. Demo text drawing

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()

Code analysis:

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

generate a font object

f1rect = f1.render_to(screen, (200,160), "World Peace", fgcolor=GOLD, size=50)

Use the render_to method to generate text and display it on the screen

Returns a Rect object that can be manipulated

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()

This example uses the render method to return a Surface object and a rect object, which need to be bound to the main layer later screen.blit(f1surf, (200,160))

4. Demonstration text operation

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])), realizes a text like a small ball by changing the position of the bound text.

Four. Summary

1. Correctly understand the application of the Surface object and the Rect object. The operation of the elements in the game is actually completed through the operation of the Rect, and the display on the game screen requires the use of the Surface object. The surface object can be generated and not displayed. Just set it on the main layer.

2. There are four ways to express the color mechanism. Choose the one that suits you. It is recommended to use the RGB or RGBA color mode. As for the value of rgb, I can’t remember it anyway. Just look it up when you use it.

3. The change of color can be carried out by manipulating the pygame.Color class, the change of RGB value, thus forming the change of color

4. The drawing of graphics generates a Rect object, which can be operated by manipulating the Rect object

5. pygame.freetype is one of the text drawing methods, and it is necessary to understand the difference between render_to and render methods.

Conclusion:

These are the main contents of the MOOC python game development introduction. The content is very basic. It is worthy of being called an introductory tutorial. Therefore, further study is required.

Guess you like

Origin blog.csdn.net/sygoodman/article/details/124358891