SoFunction
Updated on 2024-10-29

python game library pygame classic tutorial (recommended!)

I. Pygame program basic construction process

The main steps to build a game window for Pygame are as follows

1. Initialization procedure

Before programming with Pygame, we have to initialize the program with the following code

()

This code is the first code of the whole program, its role is to automatically detect whether the Pygame package is normal, and complete the initialization of modules including display (graphics module), font (font module), mixer (sound module), cursors (cursor control module) and so on.

2. Create Surface object

Surface is a window interface for Pygame programming, similar to a canvas, images and text can be displayed on the Surface, created in the following main ways

(1) Create a Surface object:

# can also be called a screen object, which is essentially a Surface object
screen = .set_mode(400,400)

(2) Create a Surface object with text:

#Creating a Surface object containing text
text = ("Ponyboy is not sloppy.",True,(255,255,255),(0,0,0))
# Draw it out via the blit method, textRect represents the position coordinates
(text,textRect)

(3) Create a Surface object containing the image:

surface_image = ("Picture path")

3.Event Listening

A good game is not without the interaction between the game and the person, through events, the person interacts with the game as he or she sees fit

The following is a simple interaction to close the game:

# all get() get events
for event in ():
    # Determine the type of event
    if  == :
        ()

4. Game Loop

Code:

while True:
    for event in ():
        if  == :
            ()
            ()
    #Update and draw screen content
    ()

Pygame Display module details

Pygame uses the methods in the Display module to create the main window of the game:

Format:

screen = .set_mode(size=(),flags=0)

-size: used to set the size of the window

-flags: function flags bit, indicates the style of the main window created, the flags parameter is as follows:

flags parameter

flag position functionality
Create a full-screen window
Creates a hardware-accelerated window that must be used in conjunction with FULLSCREEN
Creating an OPENGL Render Window
Create a window that can be resized
Creates a double-buffered window, which is recommended when HWSURFACE or OPENGL
Creating a window without a border

1. Paste the Surface object onto the main window

Code:

(source,dest,area=None,special_flage=0)

-source: Indicates the Surface object to be pasted.

-dest: coordinate position of a marker in the main window

-area: accepts a Rect object, default is None, if you provide this parameter is equivalent to the keying operation, that is, in the specified position on the screen to display the desired content

-special_flags: optional parameter, used to specify the mixing method of the color at the corresponding position

2. Setup Window Main Window

screen = .set_mode(400,400)

3. Fill the main window background, parameter value RGB

((156,156,156))

4. Set the window title

('Ponyboy is not sloppy')

5. Update screen content

()

Other methods

Method name clarification
.get_surface() Get the currently displayed Surface object
() Update the entire Surface object to be displayed to the screen
() Update the interface display of some software
() Generate a VideInfo object containing information about the display interface
.set_icon() Set the game icon in the upper left corner, the icon size size is 32*32
() Minimizes or hides the displayed main window, i.e. the Surface object.
.get_active() Returns True if the current display is on the screen, or False if the window is hidden and minimized.

Pygame Surface Creating Images

Module to create images

Grammatical format:

Surface=(size=(width,height),flags,depth)

-size: the size of the rectangular area of the Surface object.

-flage: function flag bit, there are two optional parameter values HWSURFACE and SPCALPHA, the former means that the created Surface object will be stored in the memory, the latter means that each pixel of the image contains an alpha channel.

-depth: specify the color depth of the pixel, default is adaptive mode, automatically adjusted by Pygame

Code Example:

import pygame
import sys
 
()
# Setting up the main window
screen = .set_mode((400,400))
('blue')
#Set the window title
.set_caption('Ponyboy is not sloppy')
#Creating an image
face = ((60,60),flags=)
#fill image
(color='pink')
while True:
    for event in ():
        if ==:
            ()
            ()
    #Add images to the home screen
    (face,(100,100))
    #Update screen content
    ()

Effect:

Loading images externally

Grammatical format:

('Image path').convert()

Code Example:

import pygame
import sys
 
()
# Setting up the main window
screen = .set_mode((400,400))
('white')
#Set the window title
.set_caption('Ponyboy is not sloppy')
#Load the picture
image_surface = ('C:/Users/myun/Pictures/Unknown Fire Dancer.jpg')
image_surface.fill((0,0,255),rect=(100,100,100,50),special_flags=0)
image_surface.scroll(100,60)  #Moving Pictures
while True:
    for event in ():
        if ==:
            ()
            ()
    #Add images to the home screen
    (image_surface,(0,0))
    #Update screen content
    ()

Rendering:

Surface module processing image methods:

methodologies clarification
() Drawing an image onto another image
() Modifying the format of an image
() Fill Surface images with solid colors
() Copying and moving Surface objects
.set_alpha() Set the transparency of the entire image
.get_at() Get the color value of a pixel
.set_at() Sets the color value of a pixel
.get_palette() Get the color palette for the 8-bit index of the Surface object
.map_rgb() Converts an RGBA color to a mapped color value
.set_clip() Set the clipping area for this Surface object.
() Create a new child Surface object based on the parent object
.get_offset() Get the offset of the child Surface object in the parent object
.get_size() Get the size of the Surface object

Pygame Transform image deformation

Transform Method

methodologies clarification
() Scales the image to the specified size and returns a new Surface object
() Rotate an image to a specified angle
() Rotate an image at an angle while reducing or enlarging the image to a specified magnification

V. Pygame Time Time control

1. Game pause

The module provides the following common methods

methodologies clarification
.get_ticks() Get time in milliseconds
() stall
.set_time() Creating a timer, i.e., going to perform some action every so often
() Create a time object to help us determine how many frames the game is going to run at

Code Example:

import pygame
()
screen =.set_mode((500,400))
.set_caption('Time Settings')
# Getting Time
t=.get_ticks()
#Pause the game for 3000 milliseconds
t1=(3000)
print(t1)
image_surface=('C:/Users/myun/Pictures/Unknown Fire Dancer.jpg')
while True:
    for event in ():
        if ==:
            exit()
        (image_surface,(0,0))
        ()

Effect:Load image after three seconds.

2. Setting the game's frame rate (FPS)

The Clock() method allows you to set the frame rate of the game.

methodologies clarification
() Updating the clock object
.get_time() Get the time in the last tick
.get_fps() Calculate the number of frames in the clock object

Code Example:

import pygame
()
screen =.set_mode((500,400))
.set_caption('Time Settings')
# Getting Time
t=.get_ticks()
#Pause the game for 3000 milliseconds
t1=(3000)
print(t1)
image_surface=('C:/Users/myun/Pictures/Unknown Fire Dancer.jpg')
#Creating a time object
clock = ()
while True:
    # Specify the number of looping frames through the time object, 60 loops per second
    (60)
    for event in ():
        if ==:
            exit()
        (image_surface,(0,0))
        ()

Note: Game frames are only visible during motion graphics.

Pygame Rect Area Location

Rect() method creates a rectangular area of the specified position and size.

Grammatical format:

Rect=(left,top,width,height)

Code Example:

import pygame
()
screen = .set_mode((500,300))
.set_caption('Ponyboy is not sloppy')
image_surface = ("C:/Users/myun/Pictures/")
rect1 = (50,50,100,100)
# Create a new child image (surface object) based on the original image
image_child= image_surface.subsurface(rect1)
while True:
    for event in ():
        if  == :
            exit()
    # Display the area of the subgraph on the screen
    (image_child,rect1)
    ()

Effect: A rectangle of the same size as Rect1 is intercepted from the image.

Rect on other commonly used methods:

methodologies clarification
() Copy Rectangle
() Moves a rectangular area, accepts a list parameter
.move_ip() Moving Rectangle (no return)
() Increase or decrease the rectangle
() Moving a rectangle into another rectangle
() Returns the rectangle after merging two rectangles
() Adjust or move the rectangle by aspect ratio
() Tests whether a rectangle is inside another matrix.
() Whether the test point is in the rectangle
() Test if two rectangles overlap

VII.Pygame Event Module

1. Types of events

By means of event types, user actions can be processed in an orderly, one-by-one fashion.

event

Event Type descriptive member property
        QOUIT The user presses the window's close button none
ATIVEEVENT Pygame is activated or hidden

gain,state

 KEYDOWN keypad press unicode,key,mod
KEYUP Keyboard Release key,mod
MOUSEMOTION Mouse over pos,rel,button
MOUSEBUTTONDOWN Mouse over pos,button
MOUSEBUTTONUP Mouse Release pos,button
JOYAXISMOTION Joystick or pad movement joy,axis,value
JOYBALLMOTION Joy ball moves joy,axis,value
JOYHATMOTION Joystick movement joy,axis,value
JOYBUTTONDOWN Gamepad press joy,button
JOYBUTTONUP Gamepad Release joy,button
VIDEORESIZE pygame window scaling size,w,h
VIDEOEXPOSE Pygame window partially publicized none
USEREVENT Trigger a user event event code

2. Event Handling Methods

The module provides common methods for handling events as follows:

methodologies clarification
() Gets an event from the event queue and removes it from the event queue
() Blocking until an event occurs to continue execution, if no event occurs it will remain in the blocking state.
.set_blocked() Controls which events are prohibited from entering the queue, if the parameter value is None, it means that all events are prohibited from entering the
() After calling this method, Pygame automatically handles the event queue
() will return a real event, or a None, depending on the situation.
() Detect if a certain type of event is in the queue
() Clear all events from the queue
.get_blocked() Detect if a certain type of event is banned from the queue
() Place a new event in the queue
() Create a user-defined event
.set_allowed() Controls which events are allowed into the queue

3. Handling keyboard events

Keyboard events are passed a key attribute, through which you can get the keys of the keyboard, as follows are the constants of the keyboard keys:

constant name descriptive
K_BACKSPACE

Backspace

K_TAB Tabs
K_CLEAR Clear
K_RETURN Enter.
K_PAUSE Pause
K_ESCAPE Escape key
K_SPACE

Space

K_0~K_9 0~9
K_a~k_z a~z
K_DELETE

The delete key.

K_KP0~K_KP9

0~9 of the keypad

K_F1~K_F15 F1~F15
K_UP up-pointing arrow
K_DOWN down-pointing arrow
K_RIGHT right-pointing arrow
K_LEFT left-pointing arrow
KMOD_ALT Press the Alt key at the same time

4. Handling mouse events

event clarification
MOUSEMOTION Mouse over
MOUSEBUTTONDOWN Mouse Release
MOUDEBUTTONUP Mouse Release
import pygame
from random import randint
# Initialization process
()
screen = .set_mode((450,400))
# Update the display
()
while True:
    # Waiting for an event to happen
    event = ()
    if  == :
        exit("Successful exit.")
    if  == :
        # pos Get the current position of the mouse
        print('Mouse down',)
        mx,my = 
        # Call the module to draw a circle
        (screen,(255,255,0),(mx,my),50)
        # Processed and updated to show
        ()
    if  == :
        print('Mouse pops up')
        pass
    if  == :
        print('Mouse over')
        mx, my = 
        # Randomly generated RGB color values
        r = randint(0,255)
        g = randint(0,255)
        b = randint(0,255)
        (screen, (r,g,b,),(mx, my), 50)
        # Processed and updated to show
        ()

VIII.Pygame Dra drawing functions

1. Drawing rectangles

Grammatical format:

(surface,color,rect,width)

-surface: refers to the main window

-color: This parameter is used for graphics coloring.

-rect: draws the position and size of the figure

-width: optional parameter, specify the width of the border, the default is 0, that means to fill the rectangular area

Note: When width>0, indicates the width of the wireframe, and width<0, at this time will not draw any graphics

2. Drawing polygons

Grammatical format:

(surface,color,points,width)

The rest of the parameters are the same as above, with points denoting the multiple (x,y) coordinates that make up the polygon

3. Drawing circles

Grammatical format:

(surface,color,pos,radius,width=0)

-pos: this parameter is used to specify the position of the center of the circle

-radius: the radius of the circle.

4. Drawing an ellipse

Grammatical format:

(surface,Rect,width=0)

5. Drawing arc curves

Grammatical format:

(Surface,color,Rect,start_angle,stop_angle,width=1)

-start_angle: the start angle of the arc of this segment

-stop_angle: stop angle

6. Drawing straight lines

Grammatical format:

A straight line:

(surface,color,start_pos,end_pos,width=1)

-start_pos and end_pos: the start and end positions of the line segment (x,y).

-width=1: indicates the width of the line, default is 1.

A smooth line that eliminates jaggies:

(surface,color,start_pos,end_pos,blend=1)

Multiple straight lines:

(surface,color,closed,pointlist,width=1)

-pointlist: a parameter list containing a list of point coordinates.

-closed: boolean parameter, if set to True, means that the first endpoint of the line and the last endpoint of the line should be connected.

Multiple anti-aliased straight lines:

(surface,color,closed,pointlist,blend=1)

General Summary of Drawing Methods:

Module drawing methods

methodologies clarification
() Plotting matrices
() Drawing polygons
() Drawing a circle based on its center and radius
() Drawing an ellipse
() Drawing Arcs
() Drawing Line Segments
() Drawing multiple consecutive line segments
() Draw a smooth line segment (anti-aliasing)
() Drawing multiple consecutive line segments

Code Example:

import pygame
from math import pi
# Initialization
()
# Set the home screen size
size = (500, 450)
screen = .set_mode(size)
# Set a variable that controls the main loop
done = False
#Creating a clock object
clock = ()
while not done:
    # Set the game's fps
    (10)
    for event in ():
        if  == :
            done = True  # If a closed window is detected, set done to True
    # Draw a red diagonal line of width 3
    (screen, (0, 255, 0), [0, 0], (500, 450), 3)
    # Draws multiple blue lines (continuous, non-antialiased), False means not connected at the beginning and end.
    (screen, (0, 0, 255), False, [[0, 80], [50, 90], [200, 80], [220, 30]], 1)
    # Draw a gray rectangular area, fill the area with gray
    (screen, (155, 155, 155), (75, 10, 50, 20), 0)
    # Draw a rectangular area with a wireframe width of 2
    (screen, (0, 0, 0), [150, 10, 50, 20],2)
    # Draw an ellipse with a line width of 2
    (screen, (255, 0, 0), (225, 10, 50, 20), 2)
    # Draw a solid red ellipse
    (screen, (255, 0, 0), (300, 10, 50, 20))
    # Draw a triangle with a green border (width 2)
    (screen, (100, 200, 45), [[100, 100], [0, 200], [200, 200]], 2)
    # Draw a solid blue circle, where [60,250] indicates the position of the center, 40 is the radius, and width is 0 by default.
    (screen, (0, 0, 255), [60, 250], 40)
    # Draw an arc, where 0 is the start of the arc, pi/2 is the end of the arc, and 2 is the line width.
    (screen, (255, 10, 0), (210, 75, 150, 125), 0, pi / 2, 2)
    # Refresh the display screen
    ()
# Click close to exit the pygame program
()

Rendering:

IX. Drawing of fonts ....................

The font module draws fonts

-(filename,size): get font

-(text,antialias,color,background=None): show fonts

-get_rect(): get coordinate object

Example:

import pygame,sys
from  import *
 
()
 
surface = .set_mode((500, 400), 0, 32)
.set_caption("Text drawing")
((255, 255, 255))
 
# Get the font object, you can get the system's own, you can also customize the font
fonts = .get_fonts()
fonts = 'fonts/'
basicFont = (fonts, 50)
 
# surface object
text = ('This is a string of characters', True, (255,255,255), (0,255,0))
 
# Set text position
textRect = text.get_rect()
 
 = (250, 200)
 
# Update the rendered surface object to the screen
(text,textRect)
 
# Main loop of the program
while True:
 
  # Getting events
  for event in ():
    # Determine if an event is an exit event
    if  == QUIT:
      # Exit pygame
      ()
      # Exit the system
      ()
 
  # Drawing screen content
  ()

X. Audio playback

mixer audio module

-(filename): Play the effect sound.

-(filename): load background music

Code Example:

import pygame, sys
from  import *
 
# Initialize pygame
()
 
# Set the size of the window in pixels
screen = .set_mode((500, 400))
 
# Set the title of the window
.set_caption('Audio Playback')
 
# Setting the background
((255, 255, 255))
 
# Load and play an effects audio file
sound = ('C:/Users/myun/Music/Sniper.wav')
()
 
# Load background music files
('C:/Users/myun/Music/Oh The Larceny - Light That Fire.mp3')
 
# Play background music, the first parameter is the number of times to play (-1 means infinite loop), the second parameter is to set the starting point of playback (in seconds)
(-1, 0.0)
 
# Main loop of the program
while True:
    # Getting events
    for event in ():
        # Determine if an event is an exit event
        if  == QUIT:
            # Stop playing background music
            ()
            # Exit pygame
            ()
            # Exit the system
            ()
 
    # Drawing screen content
    ()

summarize

to this article on the python game library pygame classic tutorial article is introduced to this, more related python game library pygame content please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!