“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
This series of columns will reinforce your Knowledge of Python by constantly writing games.
This column aims to quickly master PyGame while also ramping up python knowledge, so learn along.
Purpose of this blog
Load all material images at one time, and get a certain target region (subgraph) on the image by calling the name of the specified image.
You can start by copying and understanding the code, and the end result looks like this.
The code to achieve the above effect is shown below, and you can add comments in important parts to help you understand.
import pygame
import os
import sys
pygame.init()
screen = pygame.display.set_mode((400.400))
The # accept parameter limits the format of the image that is passed in
def load_graphics(path, accept=(".jpg".".png".".jpeg")) :
graphics = {}
for pic in os.listdir(path):
name, ext = os.path.splitext(pic)
if ext.lower() in accept:
img = pygame.image.load(os.path.join(path, pic))
# Determine if the image has a transparent background
if img.get_alpha():
img = img.convert_alpha()
else:
# Speed up the game loading image operation
img = img.convert()
graphics[name] = img
return graphics
def get_image(target, x, y, width, height, colorkey) :
image = pygame.Surface((width, height))
image.blit(target, (0.0), (x, y, width, height))
image.set_colorkey(colorkey)
return image
if __name__ == "__main__":
while True:
# imgs folder inside the image can be prepared by yourself, filename optional
# You can prepare pictures with various suffixes
graphics = load_graphics("./imgs")
print(graphics)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill((12.200.180))
# similar to 335,160,70,60, are measured according to different pictures, you can use the screenshot tool or the drawing board to measure.
small_img = get_image(
graphics["one_pic1"].335.160.70.60, (0.0.0))
screen.blit(small_img, (100.100))
pygame.display.update()
Copy the code
Detailed description of the code section and pothole avoidance guide
The load_graphics function calls all images in the folder and returns a dictionary with the key of the image name and the value of a Surface object loaded by pygame.image.load.
The key function to learn in this code is img.get_alpha(), which determines whether an image is transparent, i.e. with alpha.
Use pygame.surface.get_alpha () to get the transparency of the entire image. When the image has a transparent area, it will return a specific value, usually 255. In this test scenario, you can place some images without transparency in the folder and return them according to the file name. Opaque image returns None instead of 0.
PNG 255 3. PNG 255 4. PNG 255 5Copy the code
The pyGame.surface.convert () function is used to change the image (Surface object) to pixel format; The pygame.surface.convert_alpha () function is also used to change the image (Surface object) to pixel format, with an extra alpha value in the color tuple.
The difference between these two functions is the difference between transparency and transparency. These two functions convert images into a special pixel format image (implemented internally in PyGame), which makes the game render images faster. The core principle is not to go into too much detail, just use this function when writing PyGame.
In the process of code writing, it is important to remember the problems caused by Chinese names, but there is no Chinese BUG in this case. In the picture reading, if the name of the picture is set to Chinese, it can be read normally, but it is recommended to use English words for naming.
The above code, in the process of running, will also appear the following error:
pygame.error: No video mode has been set
Copy the code
This exception occurs because the game window is not initialized before the image is called, which means the following code is missing.
screen = pygame.display.set_mode((400.400))
Copy the code
Extract a region of the image
This part of the content is a new knowledge point, also need to focus on learning, the code part is as follows:
def get_image(target, x, y, width, height, colorkey) :
image = pygame.Surface((width, height))
image.blit(target, (0.0), (x, y, width, height))
image.set_colorkey(colorkey)
return image
Copy the code
The get_image function is used to get the specified image region. The function to construct the Surface object was covered in a previous blog post.
Image = PyGame.surface ((width, height)) creates a Surface object.
Image. Blit (target, (0, 0), (x, y, width, height)) draw on the Surface object created by the previous line of code. Plotted coordinate points, plotted cross sections.
Start drawing a region on target at point (0,0) of a Surface object.
Or as described in a previous blog post, slide a clear glass across an image to find a target area.
Set_colorkey and get_colorkey
The set_colorkey function is used to manipulate transparent data. The set_colorkey objective is to set the same color value as colorkeys to transparent when drawing a Surface object. Colorkeys are usually passed RGB color. Unset colorKeys.
Note that if the image in the code has been converted to transparent pixel format using convert_alpha(), the opacity setting will achieve the blending effect.
However, after using this function, the effect is not very ideal, it is recommended that transparent images or ready in advance.
The upper image is white background, the lower image is set white area transparent, the effect is not ideal
I hope you learned something new in this extra column series. If you have any questions, you can contact the eraser to solve them. Let’s play games together. The amount of practice for this column is about 1 hour every day.