Detailed explanation of Pygame game programming in Python

1. Introduction

1.1 Definition

Pygame is a popular Python game development library that provides many features that allow developers to easily create 2D games. It has good cross-platform support and can run on multiple operating systems such as Windows, MacOS, and Linux. In this article, we will introduce the characteristics and usage of the Pygame library to help you understand how to use the Pygame library for game development. It provides many operating modules, such as image module (image), sound module (mixer), input/output (mouse, keyboard, display) module, etc.

Government site:https://www.pygame.org/

1.2 Related functions

1) pygame.sprite A higher-level object that represents the game image

pygame.sprite.Sprite: A simple base class for visible game objects.
pygame.sprite.WeakSprite: A subclass of Sprite, a weak reference to its group. This means that any group it belongs to will be automatically garbage collected if it is not referenced elsewhere.
pygame.sprite.DirtySprite: A subclass of Sprite with more properties and functions.
pygame.sprite.Group: Container class used to save and manage multiple Sprite objects.
pygame.sprite.WeakDirtySprite: A subclass of WeakSprite and DirtySprite that combines the advantages of these two classes.
pygame.sprite.RenderPlain: Same as pygame.sprite.Group
pygame.sprite.RenderClear: Same as pygame.sprite.Group
pygame.sprite.RenderUpdates: Group subclass for tracking dirty updates.
pygame.sprite.OrderedUpdates: RenderUpdates subclass, draws Sprites in the order they are added.
pygame.sprite.LayeredUpdates: LayeredUpdates is a sprite group that handles layers and drawing like OrderedUpdates.
pygame.sprite.LayeredDirty: The LayeredDirty group applies to DirtySprite objects. Subclass LayeredUpdates.
pygame.sprite.GroupSingle: A group container that holds a single sprite.
pygame.sprite.spritecollide: Finds sprites in a group that intersect with another sprite.
pygame.sprite.collide_rect: Use a rectangle to detect collisions between two sprites.
pygame.sprite.collide_rect_ratio: Use a proportionally scaled rectangle to detect collisions between two sprites.
pygame.sprite.collide_circle: Use circles to detect collisions between two sprites.
pygame.sprite.collide_circle_system: Use scaled circles to detect collisions between two sprites.
pygame.sprite.collide_mask: Use a mask to detect collisions between two sprites.
pygame.sprite.groupcollide: Find all sprites that collided between two groups.
pygame.sprite.spritecollideany: Simple test if the sprite intersects with anything in the group.

2)pygame.Surface Image and screen objects

pygame.Surface.blit: Draw one image onto another image
pygame.Surface.blitz: Draw many images onto another image
pygame.Surface.convert: Change the pixel format of the image
pygame.Surface.convert_alpha: Change the pixel format of the image, including per-pixel alpha
pygame.Surface.copy: Create a new copy of Surface
pygame.Surface.fill: Fill the surface with a solid color
pygame.Surface.scroll: Move the surface image In place
pygame.Surface.set_colorkey: Set the transparent color key
pygame.Surface.get_colorkey: Get the current transparent color key
pygame .Surface.set_alpha: Set the alpha value of the complete Surface image
pygame.Surface.get_alpha: Get the current Surface transparency value
pygame.Surface.lock: Lock Surface memory for pixel access
pygame.Surface.unlock: Unlock Surface memory from pixel access
pygame.Surface.mustlock: Test whether Surface needs to be locked
pygame.Surface.get_locked: Test whether the Surface is currently locked
pygame.Surface.get_locks: Get the Surface's lock
pygame.Surface.get_at : Get the color value of a single pixel
pygame.Surface.set_at: Set the color value of a single pixel
pygame.Surface.get_at_mapped: Get the mapped color at a single pixel Value
pygame.Surface.get_palette: Get the color index palette of the 8-bit Surface
pygame.Surface.get_palette_at: Get the color of a single entry in the palette
pygame.Surface.set_palette: Set the palette of the 8-bit Surface
pygame.Surface.set_palette_at: Set the color of a single index in the 8-bit Surface palette
pygame.Surface.map_rgb: Convert color to mapped color value
pygame.Surface.unmap_rgb: Convert mapped integer color value to Color
pygame.Surface.set_clip: Set the current clipping area of ​​Surface
pygame.Surface.get_clip: Get the current clipping area of ​​Surface
pygame. Surface.subsurface: Create a new surface that references its parent
pygame.Surface.get_parent: Find the subsurface's parent
pygame.Surface.get_abs_parent: Find The top-level parent of a subsurface surface
pygame.Surface.get_offset: Finds the position of a subsurface inside a parent
pygame.Surface.get_abs_offset: Finds the position of a subsurface inside its top level Absolute position within the parent surface
pygame.Surface.get_size: Get the size of the Surface
pygame.Surface.get_width: Get the width of the Surface
pygame.Surface.get_height: Get the height of Surface
pygame.Surface.get_rect: Get the rectangular area of ​​Surface
pygame.Surface.get_bitsize: Get Surface Bit depth of pixel format
pygame.Surface.get_bytesize: Get the number of bytes used by each Surface pixel
pygame.Surface.get_flags: Get the number used for Surface Additional flags
pygame.Surface.get_pitch: Get the number of bytes used by each Surface row
pygame.Surface.get_masks: Convert between colors and mapped integers Required bitmasks
pygame.Surface.set_masks: Sets the bitmasks required to convert between colors and mapped integers
pygame.Surface.get_shifts : The bit shifts required for conversion between colors and mapped integers
pygame.Surface.set_shifts: Set the bit shifts required for conversions between colors and mapped integers
pygame.Surface.get_losses: Significant bits for converting between colors and mapped integers
pygame.Surface.get_bounding_rect: Find the smallest rectangle containing data
pygame.Surface.get_view: Returns the buffer view of Surface pixels.
pygame.Surface.get_buffer: Get the buffer object of Surface pixels.
pygame.Surface._pixels_address: Pixel buffer address
pygame.Surface.premul_alpha: Returns a copy of the surface with the RGB channels pre-multiplied by the alpha channel.

3)pygame.surfarray Manipulate image pixel data 

pygame.surfarray.array2d: Copy pixels into a two-dimensional array
pygame.surfarray.pixels2d: Put reference pixels into a two-dimensional array
pygame.surfarray.array3d: Copy pixels into 3d array
pygame.surfarray.pixels3d: Put reference pixels into 3d array
pygame.surfarray .array_alpha: Copy pixel alpha into a two-dimensional array
pygame.surfarray.pixels_alpha: Reference pixel alpha into a two-dimensional array
pygame.surfarray.array_red : Copy red pixels into a two-dimensional array
pygame.surfarray.pixels_red: Put red reference pixels into a two-dimensional array.
pygame.surfarray.array_green: Copies green pixels into a 2D array
pygame.surfarray.pixels_green: Copies green reference pixels into a 2D array.
pygame.surfarray.array_blue: Copy blue pixels into a 2D array
pygame.surfarray.pixels_blue: Copy blue reference pixels into a 2D array middle.
pygame.surfarray.array_colorkey: Copy the colorkey value into a two-dimensional array
pygame.surfarray.make_surface: Copy the array to a new surface< a i=14> pygame.surfarray.blit_array: Blit directly from array values pygame.surfarray.map_array: Map 3d array to 2d array pygame.surfarray .use_arraytype: Sets the array system used for surface arrays pygame.surfarray.get_arraytype: Gets the currently active array type. pygame.surfarray.get_arraytypes: Get the currently supported array system types.




4)python Manage the top functions of pygame

pygame.init: Initialize all imported pygame modules
pygame.quit: Uninitialize all pygame modules
pygame.get_init: If pygame is currently Initialized, it returns True
pygame.error: Standard pygame exception
pygame.get_error: Get the current error information
pygame.set_error :Set the current error message
pygame.get_sdl_version: Get the version number of SDL
pygame.get_sdl_byteorder: Get the byte order of SDL
pygame.register_quit: Register a function that is called when pygame exits
pygame.encode_string: Encode Unicode or bytes objects
pygame.encode_file_path: Convert Unicode or bytes objects to bytes object encoded as a file system path

 5)pygame.BufferProxy Array protocol view of surface pixels

This class is a buffer object Surface  object exported through the array protocol

pygame.BufferProxy.parent: Returns the Surface object of the BufferProxy, or the object that calls BufferProxy
pygame.BufferProxy.length: Returns the length of the buffer, in bytes. Similar to the len field
pygame.BufferProxy.length: Copy and return the buffer data as a str or bytes object
pygame.BufferProxy.write: Copy the words section write buffer

6)pygame.Color color display

This class is a module used to describe colors in pygame

pygame.Color.r: Gets or sets the red value of Color.
pygame.Color.g: Get or set the green value of Color.
pygame.Color.b: Get or set the blue value of Color.
pygame.Color.a: Get or set the alpha value of Color.
pygame.Color.cmy: Gets or sets the CMY representation of Color.
pygame.Color.white: Gets or sets the HSVA representation of Color.
pygame.Color.hsla: Gets or sets the HSLA representation of Color.
pygame.Color.i1i2i3: Gets or sets the I1I2I3 representation of Color.
pygame.Color.normalize: Returns the normalized RGBA value of the color.
pygame.Color. Correct_gamma: Applies a specific gamma value to a color.
pygame.Color.set_length: Set the number of elements in Color to 1, 2, 3, or 4.
pygame.Color.grayscale: Returns the grayscale of a color
pygame.Color.lerp: Returns the linear interpolation of the given Color.
pygame.Color.premul_alpha: Returns a Color in which the r, g, and b components have been multiplied by alpha.
pygame.Color.update: Set color element

7)pygame.cursors Load and compile cursor images

pygame.cursors.compile: Create binary cursor data from a simple string
pygame.cursors.load_xbm: Load cursor data from an XBM file
pygame .cursors.Cursor: pygame object representing the cursor

8)pygame.display Placement display surface 

pygame.display.init: Initialize the display module
pygame.display.quit: Cancel the initialization of the display module
pygame.display.get_init: If displayed If the module has been initialized, it returns True
pygame.display.set_mode: Initialize the window or screen for display
pygame.display.get_surface: Get the currently set display surface Reference
pygame.display.flip: Update the complete display of Surface to the screen
pygame.display.update: Update part of the screen displayed by the software< a i=7> pygame.display.get_driver: Get the name of the pygame display backend pygame.display.Info: Create a video display information object pygame.display.get_wm_info : Get information about the current window system pygame.display.get_desktop_sizes: Get the size of the active desktop pygame.display.list_modes: Get the list of available full-screen modes< /span> pygame.display.gl_get_attribute: Get the value of the OpenGL flag of the current monitor pygame.display.mode_ok: Select the best color depth for the display mode pygame.display.get_active: Return True when the display on the screen is active pygame.display.iconify: Iconize the display surface pygame.display.toggle_fullscreen: Switch between full screen and window display pygame.display.set_gamma: Change the hardware gamma ramp pygame.display.set_gamma_ramp: Change the hardware gamma ramp using a custom lookup pygame.display.set_icon: Change the system image for the display window pygame.display.set_caption: Set the current window title pygame.display.get_caption: Get the current window title pygame.display .set_palette: Set the display palette of the index display pygame.display.get_num_displays: Return the display number pygame.display.get_window_size: Return the size of the window or screen pygame.display.get_allow_screensaver: Returns whether the screen saver is allowed to run. pygame.display.set_allow_screensaver: Set whether the screensaver can run




















 9) pygame.draw Draw simple shapes on the surface, such as straight lines and ellipses

pygame.draw.rect: Draw a rectangle
pygame.draw.polygon: Draw a polygon
pygame.draw.circle: Draw a circle
pygame.draw.ellipse: Draw an ellipse
pygame.draw.arc: Draw an elliptical arc
pygame.draw. line: draw a straight line
pygame.draw.lines: draw multiple consecutive straight line segments
pygame.draw.aline: draw an anti-aliased straight line
pygame.draw.aalines: Draw multiple continuous anti-aliased straight line segments

10)pygame.event Manage incoming events from various input devices and window platforms

pygame.event.pump: Internal processing of pygame event handlers
pygame.event.get: Get events from the queue
pygame.event. poll: Get a single event from the queue
pygame.event.wait: Wait for a single event in the queue
pygame.event.peek: Test whether the event type is being queued Waiting in
pygame.event.clear: Remove all events from the queue
pygame.event.event_name: Get the string name from the event ID
pygame.event.set_blocked: Control which events are allowed in the queue
pygame.event.set_allowed: Control which events are allowed in the queue
pygame.event .get_blocked: Test whether a certain type of event is blocked by the queue
pygame.event.set_grab: Control sharing input devices with other applications
pygame.event.get_grab : Test whether the program shares input devices
pygame.event.set_keyboard_grab: Grabbing can capture system keyboard shortcuts such as Alt+Tab or Meta/Super keys.
pygame.event.get_keyboard_grab: Get the current keyboard grab status
pygame.event.post: Put new events into the queue
pygame.event.custom_type: Make a custom user event type
pygame.event.Event: pygame object used to represent events

 11)pygame.examples Various programs demonstrate the use of various pygame modules

pygame.examples.alien.main: Play the complete alien example
pygame.examples.stars.main: Run a simple starry sky example
pygame.examples.chimp.main: Hit the moving chimp
pygame.examples.moveit.main: Display animated objects on the screen
pygame.examples. fonty.main: Run font rendering example
pygame.examples.freetype_misc.main: Run FreeType rendering example
pygame.examples.vgrade.main: Display vertical gradient< /span> pygame.examples.scrap_clipboard.main: Access the clipboard< /span> pygame.examples.playmus.main: Play audio files pygame.examples.camera.main: Displays video captured in real time from a connected camera pygame.examples.testsprite.main: Display a large number of moving sprites pygame.examples.midi.main: Run a MIDI example pygame.examples.scaletest.main: Use smoothscale to interactively scale images pygame.examples.pixelarray.main: Display various pixel array generation The effect pygame.examples.cursors.main: Display two different custom cursors pygame.examples.blit_blends.main: Use an alternative to Surface.fill Additive Fill pygame.examples.blend_fill.main: Demonstrates various Surface.fill method blending options pygame.examples.joystick.main: demonstrates the joystick Features pygame.examples.headless_no_windows_needed.main: writes an image file that is a smoothly scaled copy of the input file pygame.examples.mask.main: Use collision detection to display multiple images bouncing off each other pygame.examples.glcube.main: Display animated 3D cube using OpenGL pygame.examples.liquid. main: Display animated liquid effects pygame.examples.sound_array_demos.main: Play various sndarray effects pygame.examples.sound.main: Load and play sounds pygame.examples.arraymo.main: Display various surf array effects
pygame.examples.eventlist.main: Display pygame events


















 12)pygame.font Load and render TrueType font

pygame.font.init: Initialize the font module
pygame.font.quit: Cancel the initialization of the font module
pygame.font.get_init: true if The font module has been initialized
pygame.font.get_default_font: Get the file name of the default font
pygame.font.get_sdl_ttf_version: Get the SDL_ttf version
pygame.font.get_fonts: Get all available fonts
pygame.font.match_font: Find a specific font on the system
pygame.font.SysFont: From System font creates a Font object
pygame.font.Font: Creates a new Font object from a file

 13)pygame.freetype Enhanced pygame module for loading and rendering fonts

pygame.freetype.get_error: Return the latest FreeType error
pygame.freetype.get_version: Return the FreeType version
pygame.freetype.init: Initialization The underlying FreeType library.
pygame.freetype.quit: Close the underlying FreeType library.
pygame.freetype.get_init: Returns True if the FreeType module is currently initialized.
pygame.freetype.was_init: DEPRECATED: Use get_init() instead.
pygame.freetype.get_cache_size: Returns the glyph case size
pygame.freetype.get_default_resolution: Returns the default pixel size (in dots per inch) pygame.freetype.Font: Create a new Font instance from a supported font file. pygame.freetype.get_default_font: Get the file name of the default font pygame.freetype.SysFont: Create a Font object from the system font
pygame.freetype.set_default_resolution: Set the module's default pixel size (in dots per inch)


 14)pygame.gfxdraw Anti-aliasing drawing function

pygame.gfxdraw.pixel: Draw a pixel
pygame.gfxdraw.hline: Draw a horizontal line
pygame.gfxdraw.vline: Draw a vertical line Line
pygame.gfxdraw.line: Draw a line
pygame.gfxdraw.rectangle: Draw a rectangle
pygame.gfxdraw. box: Draw a filled rectangle
pygame.gfxdraw.circle: Draw a circle
pygame.gfxdraw.aacircle: Draw an anti-aliased circle< a i=8> pygame.gfxdraw.filled_circle: Draw a solid circle pygame.gfxdraw.ellipse: Draw an ellipse pygame.gfxdraw.aaellipse: Draw an anti- Sawtooth ellipse pygame.gfxdraw.filled_ellipse: Draw a solid ellipse pygame.gfxdraw.arc: Draw an arc pygame .gfxdraw.pie: Draw a pie pygame.gfxdraw.trigon: Draw a triangle/triangle pygame.gfxdraw.atrigon: Draw anti-aliased triangle/triangle< /span> pygame.gfxdraw.bezier: Draw Bezier curve pygame.gfxdraw.textured_polygon: Draw a textured polygon pygame.gfxdraw.filled_polygon: Draw a filled polygon pygame.gfxdraw. aapolygon: Draw an anti-aliased polygon pygame.gfxdraw.polygon: Draw a polygon pygame.gfxdraw.filled_trigon: Draw a solid triangle/triangle













 15)pygame.image Add, save and save the surface

pygame.image.load: Load a new image from a file (or file-like object)
pygame.image.save: Save an image to a file (or file-like object)
pygame.image.get_sdl_image_version: Get the version number of the SDL_Image library being used
pygame.image.get_extended: Test whether the extended image format can be loaded
pygame.image.tostring: Transfer image to byte buffer
pygame.image.tobytes: Transfer image to byte buffer
pygame.image.fromstring: Create a new Surface from the byte buffer
pygame.image.frombytes: Create a new Surface from the byte buffer
pygame .image.frombuffer: Create a new Surface and share data within the byte buffer
pygame.image.load_basic: Load a new BMP image from a file (or file-like object) a> pygame.image.save_extended: Save a png/jpg image to a file (or similar file object)
pygame.image.load_extended: Load an image from a file (or file-like object)

 16)pygame.joystick Manage joystick devices

pygame.joystick.init: Initialize the joystick module.
pygame.joystick.quit: Uninitialize the joystick module.
pygame.joystick.get_init: Returns True if the joystick module has been initialized.
pygame.joystick.get_count: Returns the number of joysticks.
pygame.joystick.Joystick: Create a new joystick object.

 17)pygame.key Management key settings

pygame.key.get_focused: true if the display is receiving keyboard input from the system
pygame.key.get_pressed: Get the status of all keyboard buttons< a i=2> pygame.key.get_mods: Determine which modifier keys are being pressed pygame.key.set_mods: Temporarily set which modifier keys are pressed pygame. key.set_repeat: Control how the pressed key is repeated pygame.key.get_repeat: View how the pressed key is repeated pygame.key.name: Get the password The name of the key identifier pygame.key.key_code: Get the key identifier from the key name pygame.key.start_text_input: Start processing Unicode text input events pygame.key.stop_text_input: Stop processing Unicode text input events pygame.key.set_text_input_rect: Control the position of the candidate list








 18)pygame.locals Pygame 常量

This module contains various constants used by pygame. Its contents are automatically placed in the pygame module namespace.

19)pygame.mixeradditional voice broadcast

pygame.mixer.init: Initialize the mixer module
pygame.mixer.pre_init: Preset mixer initialization parameters
pygame.mixer .quit: Uninitialize the mixer
pygame.mixer.get_init: Test whether the mixer has been initialized
pygame.mixer.stop: Stop playing all channels
pygame.mixer.pause: Temporarily stop the playback of all channels
pygame.mixer.unpause: Resume the paused channel playback
pygame.mixer.fadeout: Gradually weaken the volume of all sounds before stopping
pygame.mixer.set_num_channels: Set the total number of playback channels
pygame.mixer.get_num_channels: Get the total number of playback channels
pygame.mixer.set_reserved: Reserve the channel from being automatically used
pygame.mixer.find_channel: Find an unused channel
pygame.mixer.get_busy: Test whether sound is mixed
pygame.mixer.get_sdl_mixer_version: Get the SDL version of the mixer
pygame. mixer.Sound: Create a new Sound object from a file or buffer object
pygame.mixer.Channel: Create a Channel object to control playback

20)pygame.mouse Manage mouse device and display

pygame.mouse.get_pressed: Get the status of the mouse button
pygame.mouse.get_pos: Get the mouse cursor position
pygame.mouse.get_rel: Get the amount of mouse movement
pygame.mouse.set_pos: Set the mouse cursor position
pygame.mouse.set_visible: Hide or show the mouse cursor
pygame.mouse.get_visible: Get the current visible status of the mouse cursor
pygame.mouse.get_focused: Check whether the monitor is receiving mouse input
pygame.mouse. set_cursor: Set the mouse cursor to the new cursor
pygame.mouse.get_cursor: Get the current mouse cursor

21)pygame.mixer.music Play streaming music track

pygame.mixer.music.load: Load music files for playback
pygame.mixer.music.unload: Unload currently loaded music to release resources
pygame.mixer.music.play: Start playing music stream
pygame.mixer.music.rewind: Restart music
pygame.mixer.music.stop : Stop music playback
pygame.mixer.music.pause: Temporarily stop music playback
pygame.mixer.music.unpause: Resume paused music
pygame.mixer.music.fadeout: Stop music playback after fading out
pygame.mixer.music.set_volume: Set music volume
pygame.mixer .music.get_volume: Get the music volume
pygame.mixer.music.get_busy: Check whether the music stream is playing
pygame.mixer.music.set_pos: Set playback Position
pygame.mixer.music.get_pos: Get music playback time
pygame.mixer.music.queue: Queue sound files to follow the current pygame.mixer.music.get_endevent: Get the events sent by the channel when playback stops
pygame.mixer.music.set_endevent: Let the music send events when playback stops

22)pygame.PixelArray Manipulate image pixel data

pygame.PixelArray.surface: Get the Surface used by PixelArray.
pygame.PixelArray.itemsize: Returns the byte size of the pixel array item
pygame.PixelArray.my: Returns the dimension.
pygame.PixelArray.shape: Returns the array size.
pygame.PixelArray.strides: Returns the byte offset for each array dimension.
pygame.PixelArray.make_surface: Create a new Surface from the current PixelArray.
pygame.PixelArray.replace: Replace the color passed in PixelArray with another color.
pygame.PixelArray.extract: Extracts the passed color from the PixelArray.
pygame.PixelArray.compare: Compares a PixelArray with another PixelArray.
pygame.PixelArray.transpose: Swap the x-axis and y-axis.
pygame.PixelArray.close: Close the PixelArray and release the Surface lock.

23)pygame.Rect Rectangular living container


pygame.Rect.copy: Copy the rectangle
pygame.Rect.move: Move the rectangle
pygame.Rect.move_ip: Move the rectangle into place< /span> pygame.Rect.colliderect: Test whether two rectangles overlap pygame.Rect.collidedictall: Test whether all rectangles in the dictionary intersect pygame. Rect.collidedict: Test whether a rectangle in the dictionary intersects pygame.Rect.collideobjectsall: Test whether all objects in the list intersect pygame.Rect.collideobjects: Test whether any objects in the list intersect pygame.Rect.collidelistall: Test whether all rectangles in the list intersect pygame.Rect.collidelist: Test whether a rectangle in the list intersects pygame.Rect.collidepoint: Test whether a point is inside a rectangle pygame.Rect.contains: Test whether a rectangle is in Inside another rectangle pygame.Rect.normalize: Correct negative dimensions pygame.Rect.fit : Resize and move the rectangle according to aspect ratio pygame.Rect.unionall_ip: Union of many rectangles pygame.Rect.unionall: Union of many rectangles pygame.Rect.union_ip: Connect two rectangles into one in place pygame.Rect.union: Merge two rectangles into one pygame.Rect.clipline: Clip a line within the rectangle pygame.Rect.clip: Clip a rectangle within another rectangle pygame.Rect.clamp_ip: Move the rectangle Move to another rectangle pygame.Rect.clamp: Move the rectangle into another rectangle pygame. Rect.update: Set the position and size of the rectangle pygame.Rect.scale_by_ip: Increase or reduce the rectangle size in place pygame.Rect.scale_by: Scale the rectangle by the given multiplier pygame.Rect.inflate_ip: Increase or reduce the size of the rectangle in place
pygame.Rect.inflate: Increase or reduce the size of the rectangle






















24)pygame.scrap Native clipboard access

pygame.scrap.init: Initialize the scrap module.
pygame.scrap.get_init: Returns True if the scrap module is currently initialized.
pygame.scrap.get: Get the specified type of data from the clipboard.
pygame.scrap.get_types: Get a list of available clipboard types.
pygame.scrap.put: Put data into the clipboard.
pygame.scrap.contains: Checks whether data of a given type is available in the clipboard.
pygame.scrap.lost: Indicates whether the pygame application has lost clipboard ownership.
pygame.scrap.set_mode: Set the clipboard access mode.

25)pygame.sndarray Speech sound sound hon number station

pygame.sndarray.array: Copy sound samples into an array
pygame.sndarray.samples: Reference sound samples into an array
pygame .sndarray.make_sound: Convert the array to a Sound object
pygame.sndarray.use_arraytype: Set the array system for the sound array
pygame.sndarray.get_arraytype: Get The currently active array type.
pygame.sndarray.get_arraytypes: Get the currently supported array system types.

26)pygame.tests 测试pygame

pygame.tests.run: Run the pygame unit test suite

27)pygame.time Manage time and frame rate

pygame.time.get_ticks: Get the time in milliseconds
pygame.time.wait: Pause the program for a period of time
pygame.time. delay: Pause the program for a period of time
pygame.time.set_timer: Create events repeatedly in the event queue
pygame.time.Clock: Create an object to help track time

28)pygame.transform Resize and move the image

pygame.transform.flip: Flip vertically and horizontally
pygame.transform.scale: Resize to new resolution
pygame.transform.scale_by : resize to new resolution using scalar
pygame.transform.rotate: rotate image
pygame.transform.rotozoom: filter scaling and rotation< a i=5> pygame.transform.scale2x: Specialized image multiplier pygame.transform.smoothscale: Smoothly scale surfaces to arbitrary sizes pygame.transform .smoothscale_by: Resize to new resolution using scalar pygame.transform.get_smoothscale_backend: Return the smoothscale filter version in use: "GENERIC", "MMX" or "SSE" pygame.transform.set_smoothscale_backend: Set the smoothscale filter version to one of the following: "GENERIC", "MMX" or "SSE" pygame.transform.chop: Get Copies of images with inner regions removed pygame.transform.laplacian: Find edges in surfaces pygame.transform.average_surfaces: Find averages from multiple surfaces Surface. pygame.transform.average_color: Find the average color of the surface pygame.transform.grayscale: Grayscale the surface pygame.transform.threshold: Find which and how many pixels in the surface are within the threshold of "search_color" or "search_surf".










2. Installation and use of Pygame

1. Installation

pip install pygame

2. Application cases

1) Press the keys (Alt + W/A/S/D) to move the ball

# -*- coding:utf-8 -*-
import pygame

# 初始化pygame
pygame.init()

# 设置窗口标题
title = "Pygame应用案例-按键移动的小球"
pygame.display.set_caption(title)

screen = pygame.display.set_mode((1280, 720))
clock = pygame.time.Clock()
running = True
dt = 0

player_pos = pygame.Vector2(screen.get_width() / 2, screen.get_height() / 2)

while running:
    # 事件轮询 - pygame.QUIT 事件表示用户单击X关闭您的窗口
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 用一种颜色填充屏幕以擦除上一帧中的任何内容
    screen.fill("purple")

    pygame.draw.circle(screen, "red", player_pos, 40)

    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        player_pos.y -= 300 * dt
    if keys[pygame.K_s]:
        player_pos.y += 300 * dt
    if keys[pygame.K_a]:
        player_pos.x -= 300 * dt
    if keys[pygame.K_d]:
        player_pos.x += 300 * dt

    # 更新全部显示 
    pygame.display.flip()

    # 将FPS限制为60
    # dt是自上一帧以来的增量时间(以秒为单位),用于帧速率
    dt = clock.tick(60) / 1000

pygame.quit()

2) Small ball that moves according to rules

# -*- coding:utf-8 -*-
import sys
import pygame

# 初始化pygame
pygame.init()

# 设置窗口标题
title = "Pygame应用案例-规则移动的小球"
pygame.display.set_caption(title)

# 显示窗口
width = 800
height = 600
screen = pygame.display.set_mode((width, height))  

ball = pygame.image.load("ball.png")  # 加载图片
ballrect = ball.get_rect()  # 根据图片大小获取矩形区域

speed = [5, 5]  # 设置移动的X轴、Y轴距离
clock = pygame.time.Clock()  # 创建时钟对象
# 执行死循环,确保窗口一直显示
while True:

    # 表示每秒钟60次帧刷新
    clock.tick(60)

    # 检查事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # 如果点击关闭窗口,则退出
            pygame.quit()  # 退出pygame
            sys.exit()

    ballrect = ballrect.move(speed)  # 通过再次赋值移动小球
    # 碰到左右边缘
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]  #如果碰到边距则反方向移动
    # 碰到上下边缘
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]

    # 填充颜色
    screen.fill("purple")
    # 此函数是将图片推送到窗口上,第一个参数为图片第二个参数为图片位置
    screen.blit(ball, ballrect) 
    # 更新全部显示 
    pygame.display.flip()  
 
pygame.quit()

More game cases can be downloaded and viewed from the official website (https://www.pygame.org/tags/all) https://www.pygame.org/tags/all a> 

Guess you like

Origin blog.csdn.net/m0_68949064/article/details/134599850