SoFunction
Updated on 2024-11-12

Python Color Classes and Text Drawing Mastered from Scratch

video

Watch the video

Objects used in Pygame to describe colors.

Color(name) -> Color, for example:Color("gray")

Color(r, g, b, a) -> Color, for example:Color(190, 190, 190, 255)

Color(rgbvalue) -> Color, for example:Color("#BEBEBEFF")

w3schools color picker, select any color you want, you canIt's here.Find it.

Pygame uses the Color class to represent RGBA color values, each of which can take values in the range 0 to 255. When no alpha value is given, the default is 255 (opaque).

The "RGB value" can be a color name, a string in HTML color format, a string as a hexadecimal number, or an integer pixel value in the following HTML format#rrggbbaaThe "rr", "gg", "bb", and "aa" are all 2-bit hexadecimal numbers, and the "aa" for alpha is optional. The "aa" for alpha is optional. A hexadecimal string is composed as follows0xrrggbbaaAnd, of course, the "aa" is optional.

The following program lists pygame's predefined colors

from pprint import pprint
import pygame as pg
pprint()

Methods & Properties

- Get or set the red value of the Color object

- Get or set the green value of the Color object

- Get or set the blue value of the Color object

- Gets or sets the alpha value and transparency of the Color object.

- Get or set the CMY value represented by the Color object.

- Get or set the HSVA value represented by the Color object.

- Get or set the HSLA value represented by the Color object.

.i1i2i3 - Get or set the I1I2I3 value represented by the Color object.

() - Returns the normalized RGBA value of the Color object

.correct_gamma() - Apply a certain gamma value to adjust the Color object

.set_length() - Sets the length (number of members) of the Color object

typical example

Keep the background of the window changing

import pygame, sys
()
screen_size = 640, 480
screen = .set_mode(screen_size)
.set_caption("pygame color")
GOLD = (255,251,0)
RED = ('red')
WHITE = (255, 255, 255)
GREEN = ('green')
color_list = [GOLD,RED,WHITE,GREEN]
fclock = ()
running = True
i = 0
while running:
	(1)
	for e in ():
		if  == :
			running = False
	i = i + 1
	i = 0 if i > 3 else i
	(color_list[i])
	()
()

Difference between Rect and Surface objects

Indicates a drawing layer, or drawing plane, or layer, which is used to indicate the effect of drawing a layer, text, or image that would not be displayed if it were not drawn on the main layer.

leave it (to sb).set_mode()Generates a master layer, which is a Surface object that is used to draw other layers on top of the master layer using theblit()methodologies

After drawing the graphic, a rectangular Rect class is returned to represent the shape of the

Classes expressing a rectangular area, Pygame utilizes the Rect class to manipulate graphics, images, text, and other information. Corresponds to an area of the current main layer that specifies the rectangular area drawn by the layer.

Drawing of text

The location of the system font:

Copy the Microsoft Black to the "fonts" folder.

class: draws text in a specific font to the screen, the text can't be used directly with theprint()Instead, it is drawn in pixels based on the font's dot-matrix.

pygame packages are not automatically imported when loading thefreetype. This module must be explicitly imported to be used.

import pygame
import 

New in pygame 1.9.2: freetype

Commonly used methods

1.

Creates a new instance of Font from a supported font file.

Font(file, size=0, font_index=0, resolution=0, ucs4=False) -> Font

Parameters:

fileCan be a string representing the font filename, a class file object containing the font, or None; if None, the default Pygame font is used.

(Optional) The size parameter can be specified to set the default size of the text, which determines the size of the rendered characters. The size can also be passed explicitly to each method call. Because of the way the caching system works, specifying the default size on the constructor does not mean that manually passing the size on every function call will result in a performance gain. If the font is a bitmap and no size is given, the default size is set to the first available size of the font.

2. ()

Returns the rendered text as a surface

render(text, fgcolor=None, bgcolor=None, style=STYLE_DEFAULT, rotation=0, size=0) -> (Surface, Rect)

Returns a new Surface with the text rendered to it in the color given by 'fgcolor'. If no foreground color is given, the default foreground color is usedfgcolor. If givenbgcolor, Surface will be filled with this color.

The return value is a tuple: newSurface and bounding rectangle give the size and origin of the rendered text.

If an empty string is passed for the text, the returned Rect is zero width and font height.

3. .render_to() renders the text onto the existing surfacerender_to(surf, dest, text, fgcolor=None, bgcolor=None, style=STYLE_DEFAULT, rotation=0, size=0) -> Rect Renders the string text to the object, located at dest, the (x, y) surface coordinate pair. If x or y is not an integer, convert it to an integer if possible. Accepts the first two terms as any sequence of x and y position elements, including Rect instances. As with render(), the fgcolor, style, rotation, and size parameters may be selected.

def word_wrap(surf, text, font, color=(0, 0, 0)):
     = True
    words = (' ')
    width, height = surf.get_size()
    line_spacing = font.get_sized_height() + 2
    x, y = 0, line_spacing
    space = font.get_rect(' ')
    for word in words:
        bounds = font.get_rect(word)
        if x +  +  >= width:
            x, y = 0, y + line_spacing
        if x +  +  >= width:
            raise ValueError("word too wide for the surface")
        if y +  -  >= height:
            raise ValueError("text to long for the surface")
        font.render_to(surf, (x, y), None, color)
        x +=  + 
return x, y

Word version of the blob game

import pygame, sys
import 
()
size = screen_width, screen_height = 640, 480
screen = .set_mode(size)
.set_caption('Wordplay')
BLACK = ('black')
GOLD = (255,251,0)
font1 = ("C://Windows//Fonts//", 28)
font_surface,font_rect = ("Little Workshop", fgcolor=GOLD, size=50)
pos = [screen_width // 2, screen_height // 2]
speed = [1,1]
fps = 60
fclock = ()
while True:
	(fps)
	for e in ():
		if  == :
			()
	if pos[0] < 0 or pos[0] + font_rect.width > screen_width:
		speed[0] = -speed[0]
	if pos[1] < 0 or pos[1] + font_rect.height > screen_height:
		speed[1] = -speed[1]
	pos[0] = pos[0] + speed[0]
	pos[1] = pos[1] + speed[1]
	(BLACK)
	(font_surface,(pos[0],pos[1]))
	()

to this article on Python Color class and text drawing zero-based mastery of the article is introduced to this, more related Python Color class and text drawing content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!