PyGame is a set of python modules specially written for games, which is highly portable. The following will be a brief introduction to the methods provided in Pygame, which will be a simple aircraft war demo. Scan the bottom two dimensional code, and pay attention to my official account in reply to the "aircraft war". You can get the code address of demo, the demo material (color picture material, WeChat classic black and white material, sound effect).
Main contents of this paper
- Through the example demonstration window drawing and a brief description of its required functions
- Brief description of picture movement, moving pictures through user events and required functions
- Brief description of collision detection and required functions
- Brief description of audio loading and required functions
- Achievement display
environment
- python3.6+
- windows/linux
Module installation
pip install pygame
>* * game window establishment and brief description of required functions**
import os import time import pygame # Screen width SCREEN_WIDTH = 500 # Screen height SCREEN_HEIGHT = 250 # Picture absolute path IMG_PATH = os.path.join(os.getcwd(), "img") def main(): # Initialize display module pygame.display.init() # create a window screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # Set window title pygame.display.set_caption("python Small demo Aircraft war") # Set window icon pygame.display.set_icon(pygame.image.load(os.path.join(IMG_PATH, "icon.jpg"))) # Load background picture background = pygame.image.load(os.path.join(IMG_PATH, "test_bj.png")) while True: # Draws a background picture onto the window screen.blit(background, (0, 0)) # Update screen content pygame.display.update() time.sleep(0.02) if __name__ == "__main__": main()
See the following effects:
x. y is drawn manually, so that you can more intuitively see the coordinate axis of the window
Brief description of required functions
display.init() -> None # This function only initializes the display module and does not return anything # If other methods are not initialized when using display, they will be called automatically display.set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface # This function creates and returns a Surface window object # Parameters: # size=(0, 0) set the window size. The first is the screen width and the second is the window height # flags controls the display type you want, for example, whether the screen is full. Optional parameters: # pygame.FULLSCREEN: create a full screen # pygame.DOUBLEBUF: double buffering mode, recommended for use with HWSURFACE or OPENGL # pygame.HWSURFACE: hardware acceleration, which can only be used under FULLSCREEN # pygame.OPENGL: create an OPENGL rendered display # pygame.RESIZABLE: create a resizable window # pygame.NOFRAME: create a window without borders and controls # You can use bitwise or to select multiple parameters, such as: # flags = pygame.OPENGL | pygame.FULLSCREEN # The depth parameter indicates the number of color digits. It is not recommended to pass. The best color depth will be selected by default # display window index, 0 by default # When vsync passes in 1, you can get the vertical synchronization display. Only when pygame.OPENGL and # Only pygame.FULLSCREEN can pass values display.set_caption(title, icontitle=None) -> None # Set window title # Parameters: # Title The title of the window # icontitle some systems support switching the title bar when the smallest window is available display.set_icon(Surface) -> None # Set window LOGO # Parameters: # Surface can pass in any surface object as an icon, but most systems require a size of 32 * 32 display.update(rectangle=None) -> None display.update(rectangle_list) -> None # Update the screen content display. If it is called when pygame.OPENGL is set, an exception will be triggered # Parameters: # rectangle a rectangular area # rectangle_list multiple rectangular areas # If you pass in None or an empty list, the entire window will be updated
image.load(filename) -> Surface # Load the image and return a Surface object. pygame supports pictures in common PNG, JPG, GIF and other formats #Parameters: # filename image path, compatible with the running environment. The path is recommended to be obtained through os.path.join()
Surface.blit(source, dest, area=None, special_flags=0) -> Rect # Draw the image onto another image, and the return value is a Rect object representing the rectangular area drawn on the screen # Parameters: # source the Surface instance object of the rectangular image # dest is the coordinate object, the coordinates drawn on the screen # Area means to take out the drawn from the area area area of the score to the Surface object # Combined with the above example # background = pygame.image.load(os.path.join(IMG_PATH, "test_bj.png")) # screen.blit(background, (0, 0)) # Is to draw the background picture to the 0, 0 coordinates of the screen Surface.get_rect(**kwargs) -> Rect # Gets the rectangular area of the Surface. The rectangular area always starts from coordinates 0 and 0, and the width and height are the same as the size of the picture # Returns a rect object that records the attribute information of the Surface, such as: # rect.x Surface object x-axis coordinates # rect.y Surface object Y-axis coordinates # Rect.width the width of the surface object # The height of the rect.height Surface object
Picture movement, moving pictures through user events
The above code has been able to create the game window and load the background image. Now create the hero and move by changing the coordinates
import os import time import pygame # Screen width SCREEN_WIDTH = 500 # Screen height SCREEN_HEIGHT = 250 # Picture absolute path IMG_PATH = os.path.join(os.getcwd(), "img") class HeroPlane(object): def __init__(self): super(HeroPlane, self).__init__() self.image = pygame.image.load(os.path.join(IMG_PATH, "hero_show_1.png")) self.rect = self.image.get_rect() self.rect.x = 0 # Aircraft x-axis position self.rect.y = int(SCREEN_HEIGHT - self.rect.height) / 2 # Aircraft y-axis position self.is_running = True self.bullet_list = pygame.sprite.Group() self.last_time = time.time() def move_level(self, level): # Prevent the aircraft from moving out of the screen and increase judgment add_level = self.rect.x + level if 0 <= add_level <= SCREEN_WIDTH - self.rect.width: self.rect.x = add_level elif add_level < 0: self.rect.x = 0 elif add_level > SCREEN_WIDTH - self.rect.width: self.rect.x = SCREEN_WIDTH - self.rect.width def move_vertical(self, vertical): add_vertical = self.rect.y + vertical if 0 <= add_vertical <= SCREEN_HEIGHT - self.rect.height: self.rect.y = add_vertical elif add_vertical < 0: self.rect.y = 0 elif add_vertical > SCREEN_HEIGHT - self.rect.height: self.rect.y = SCREEN_HEIGHT - self.rect.height def main(): pygame.display.init() # Initialize display module # pygame.display.init() # create a window screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # Set window title pygame.display.set_caption("python Small demo Aircraft war") # Set window icon pygame.display.set_icon(pygame.image.load(os.path.join(IMG_PATH, "icon.jpg"))) # Load background picture background = pygame.image.load(os.path.join(IMG_PATH, "test_bj.png")) # Initialize hero class hero = HeroPlane() def update_hero(): hero.move_level(2) screen.blit(hero.image, (hero.rect.x, hero.rect.y)) while True: # Draws a background picture onto the window screen.blit(background, (0, 0)) # Update the hero's position on the screen update_hero() # Update screen content pygame.display.update() time.sleep(0.02) if __name__ == "__main__": main()
The implementation effect is as follows:
Loading the hero and moving the hero is actually changing the drawing position of the picture on the screen. The time.sleep of the main function can also be replaced with pygame.time.Clock.tick Method, but in this example, the effect deviation is not far, so the time module provided by pygame.time is not used
Although the above code can realize the hero's movement, it cannot control the hero's movement according to the player's operation. At this time, we need to provide specific keyboard or mouse events to control the hero's movement. In the following example, press and hold the mouse to realize the aircraft movement
import os import sys import time import pygame # Screen width SCREEN_WIDTH = 500 # Screen height SCREEN_HEIGHT = 250 # Picture absolute path IMG_PATH = os.path.join(os.getcwd(), "img") # Mouse button identification MOUSE_MOVE = False class HeroPlane(object): def __init__(self): super(HeroPlane, self).__init__() self.image = pygame.image.load(os.path.join(IMG_PATH, "hero_show_1.png")) self.rect = self.image.get_rect() self.rect.x = 0 # Aircraft x-axis position self.rect.y = int(SCREEN_HEIGHT - self.rect.height) / 2 # Aircraft y-axis position self.is_running = True self.bullet_list = pygame.sprite.Group() self.last_time = time.time() def move_level(self, level): # Prevent the aircraft from moving out of the screen and increase judgment if 0 <= level <= SCREEN_WIDTH - self.rect.width: self.rect.x = level elif level < 0: self.rect.x = 0 elif level > SCREEN_WIDTH - self.rect.width: self.rect.x = SCREEN_WIDTH - self.rect.width def move_vertical(self, vertical): if 0 <= vertical <= SCREEN_HEIGHT - self.rect.height: self.rect.y = vertical elif vertical < 0: self.rect.y = 0 elif vertical > SCREEN_HEIGHT - self.rect.height: self.rect.y = SCREEN_HEIGHT - self.rect.height def main(): pygame.init() # Initialize display module pygame.display.init() # create a window screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # Set window title pygame.display.set_caption("python Small demo Aircraft war") # Set window icon pygame.display.set_icon(pygame.image.load(os.path.join(IMG_PATH, "icon.jpg"))) # Load background picture background = pygame.image.load(os.path.join(IMG_PATH, "test_bj.png")) # Initialize hero class hero = HeroPlane() def event_check(): """ Event detection, here is a simple example return: """ global MOUSE_MOVE for event in pygame.event.get(): if event.type == pygame.QUIT: # Exit the program after receiving the exit event pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: MOUSE_MOVE = True elif event.type == pygame.MOUSEBUTTONUP: MOUSE_MOVE = False if MOUSE_MOVE: x, y = pygame.mouse.get_pos() hero.move_level(x) hero.move_vertical(y) def update_hero(): screen.blit(hero.image, (hero.rect.x, hero.rect.y)) while True: # event detection event_check() # Draws a background picture onto the window screen.blit(background, (0, 0)) # Update the hero's position on the screen update_hero() # Update screen content pygame.display.update() time.sleep(0.02) if __name__ == "__main__": main()
The implementation effect is as follows:
Brief description of required functions
event.get(eventtype=None) -> Eventlist event.get(eventtype=None, pump=True) -> Eventlist # Get event queue # Parameters: # eventtype can pass in the event list you want to listen to. If not, all events triggered by users will be returned # If only three events are listened to in the above example, you can also: # pygame.event.get([pygame.QUIT, pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP]) # However, if the specified type of event is set, other events will not be obtained and stored in the event queue, which may cause the event queue to be full # pump defaults to False. If it is set to True, event.pump() will be called # Return to event list # Common event types: # Event generation path parameters # QUIT user presses the close button none # KEYDOWN keyboard is pressed unicode, key, mod # KEYUP keyboard is released key, mod # MOUSEMOTION mouse movement pos, rel, buttons # MOUSEBUTTONDOWN mouse press pos, button # MOUSEBUTTONUP mouse release pos, button # USEREVENT user defined event code # Common events are listed above. For more events and methods, click the document link above to view the document
- pygame.key module for handling keyboard , when the keyboard is pressed or released, pygame.event.get() can obtain pygame.KEYDOWN or pygame.KEYUP events. Both events have key and mod attributes: key represents each integer ID on the keyboard; Mod represents the modified bitmask when the event occurs.
In the above example, if you want to press and hold the keyboard ⬅,⬆,⬇,➡ Control hero, you can modify the event handling function to:
def event_check(): """ Event detection, here is a simple example return: """ # Set the KEYDOWN flag bit. 0 indicates that the keyboard has been released, and 1, 2, 3 and 4 respectively represent ⬅,⬆,⬇,➡ global KEYDOWN for event in pygame.event.get(): if event.type == pygame.QUIT: # Exit the program after receiving the exit event pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: KEYDOWN = 1 elif event.key == pygame.K_UP: KEYDOWN = 2 elif event.key == pygame.K_DOWN: KEYDOWN = 3 elif event.key == pygame.K_RIGHT: KEYDOWN = 4 elif event.type == pygame.KEYUP: KEYDOWN = 0 if KEYDOWN: if KEYDOWN == 1: hero.move_level(hero.rect.x - 5) elif KEYDOWN == 2: hero.move_vertical(hero.rect.y - 5) elif KEYDOWN == 3: hero.move_vertical(hero.rect.y + 5) else: hero.move_level(hero.rect.x + 5)
Common keyboard constants are listed below (for more keyboard constants, click the connection above to view the document):
KeyASCII | describe |
---|---|
K_BACKSPACE | Backspace |
K_TAB | Tab |
K_CLEAR | Clear key |
K_RETURN | Enter |
K_ESCAPE | Exit key (Escape) |
K_DELETE | delete key |
K_0 - K_9 | 0 - 9 |
K_a - K_z | a - z |
K_KP0 - K_KP9 | 0 - 9 (keypad) |
K_UP | up arrow |
K_DOWN | down arrow |
K_RIGHT | right arrow |
K_LEFT | left arrow |
>* * collision detection and brief description of required functions * * in the above code, we have realized the creation of heroes and can control the movement of heroes through events. Next, we can create an enemy aircraft according to the method of creating heroes and explode by collision between heroes and enemy aircraft
import os import sys import time import pygame # Screen width SCREEN_WIDTH = 500 # Screen height SCREEN_HEIGHT = 250 # Picture absolute path IMG_PATH = os.path.join(os.getcwd(), "img") # Mouse button identification MOUSE_MOVE = False # Long press the identification bit on the keyboard KEYDOWN = 0 class HeroPlane(object): def __init__(self): super(HeroPlane, self).__init__() self.image = pygame.image.load(os.path.join(IMG_PATH, "hero_show_1.png")) self.rect = self.image.get_rect() self.rect.x = 0 # Aircraft x-axis position self.rect.y = int(SCREEN_HEIGHT - self.rect.height) / 2 # Aircraft y-axis position self.is_running = True def move_level(self, level): # Prevent the aircraft from moving out of the screen and increase judgment if 0 <= level <= SCREEN_WIDTH - self.rect.width: self.rect.x = level elif level < 0: self.rect.x = 0 elif level > SCREEN_WIDTH - self.rect.width: self.rect.x = SCREEN_WIDTH - self.rect.width def move_vertical(self, vertical): if 0 <= vertical <= SCREEN_HEIGHT - self.rect.height: self.rect.y = vertical elif vertical < 0: self.rect.y = 0 elif vertical > SCREEN_HEIGHT - self.rect.height: self.rect.y = SCREEN_HEIGHT - self.rect.height class EnemyPlane(pygame.sprite.Sprite): def __init__(self): super(EnemyPlane, self).__init__() self.image = pygame.image.load(os.path.join(IMG_PATH, "mp_show_3.png")) self.rect = self.image.get_rect() self.rect = self.image.get_rect() self.rect.x = int(SCREEN_WIDTH - self.rect.width) # Aircraft x-axis position self.rect.y = int(SCREEN_HEIGHT - self.rect.height) / 2 # Aircraft y-axis position self.is_running = True def main(): pygame.init() # Initialize display module pygame.display.init() # create a window screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # Set window title pygame.display.set_caption("python Small demo Aircraft war") # Set window icon pygame.display.set_icon(pygame.image.load(os.path.join(IMG_PATH, "icon.jpg"))) # Load background picture background = pygame.image.load(os.path.join(IMG_PATH, "test_bj.png")) # Initialize hero hero = HeroPlane() # Initialize enemy aircraft enemy = EnemyPlane() def event_check(): """ Event detection, here is a simple example return: """ global MOUSE_MOVE for event in pygame.event.get(): if event.type == pygame.QUIT: # Exit the program after receiving the exit event pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: MOUSE_MOVE = True elif event.type == pygame.MOUSEBUTTONUP: MOUSE_MOVE = False if MOUSE_MOVE: x, y = pygame.mouse.get_pos() hero.move_level(x) hero.move_vertical(y) # def event_check(): # """ # Event detection, here is a simple example # return: # """ # # Set the KEYDOWN flag bit. 0 indicates that the keyboard has been released, and 1, 2, 3 and 4 respectively represent ⬅,⬆,⬇,➡ # global KEYDOWN # # for event in pygame.event.get(): # if event.type == pygame.QUIT: # # Exit the program after receiving the exit event # pygame.quit() # sys.exit() # elif event.type == pygame.KEYDOWN: # if event.key == pygame.K_LEFT: # KEYDOWN = 1 # elif event.key == pygame.K_UP: # KEYDOWN = 2 # elif event.key == pygame.K_DOWN: # KEYDOWN = 3 # elif event.key == pygame.K_RIGHT: # KEYDOWN = 4 # elif event.type == pygame.KEYUP: # KEYDOWN = 0 # # if KEYDOWN: # if KEYDOWN == 1: # hero.move_level(hero.rect.x - 5) # elif KEYDOWN == 2: # hero.move_vertical(hero.rect.y - 5) # elif KEYDOWN == 3: # hero.move_vertical(hero.rect.y + 5) # else: # hero.move_level(hero.rect.x + 5) def update_hero(): screen.blit(hero.image, (hero.rect.x, hero.rect.y)) def update_enemy(): screen.blit(enemy.image, (enemy.rect.x, enemy.rect.y)) def check_crash(): is_crash = pygame.sprite.collide_rect(hero, enemy) if is_crash: # First show the plane explosion, and then write the game over prompt in the middle of the screen screen.blit(pygame.image.load(os.path.join(IMG_PATH, "ex_2.png")), (hero.rect.x, hero.rect.y)) screen.blit(pygame.image.load(os.path.join(IMG_PATH, "ex_2.png")), (enemy.rect.x, enemy.rect.y)) game_over = pygame.font.Font(None, 100) game_over = game_over.render("game over", True, (220, 20, 60)) screen.blit(game_over, [int(SCREEN_WIDTH / 2 - game_over.get_width() / 2), int(SCREEN_HEIGHT / 2)]) while True: # event detection event_check() # Draws a background picture onto the window screen.blit(background, (0, 0)) # Update the hero's position on the screen update_hero() # Update enemy position on screen update_enemy() # collision detection check_crash() # Update screen content pygame.display.update() time.sleep(0.02) if __name__ == "__main__": main()
The implementation effect is as follows:
Brief description of required functions
- pygame.sprite Basic game object class. In the above example, our hero and enemy aircraft inherit pygame.sprite.Sprite, which is convenient for us to omit the steps of building wheels, such as collision detection.
sprite.collide_rect(left, right) -> bool # Detect whether two objects that inherit pygame.sprite.Sprite and have rectangular area properties collide # This method will judge whether a collision has occurred according to the rect attribute of the object # Parameters: # left first object, such as hero # right the second object, such as hero # Returns the bool value. If true, there is a collision. If false, there is no collision # In this example, there is only one enemy aircraft and one hero, but if the hero needs to collide with multiple enemy aircraft # Or whether the bullet sent by the hero hit the enemy aircraft, which produces one to many, many to many detection # In this case, you can use sprite.Group to complete this method sprite.Group() -> Group # Container class for saving and managing multiple Sprite objects # Returns a group object sprite.Group.add(*sprites) -> None # Add a sprites to the group sprite.spritecollide(sprite, group, dokill, collided = None) -> Sprite_list # Find out if a sprite collides with the sprite in sprite.Group() # For one to many collision detection # Parameters: # Sprite single sprite object # Group a group object that contains multiple sprite objects # dokill bool value. If true, the collided sprite object will be removed from the group in case of collision # Collapsed is a function to judge collision. The parameters are two sprite objects, and you need to return bool value if you # The sprite object also has the rect attribute set in the example, which can not be passed # Returns all objects that collide with Sprite. If not, returns an empty Sprite_list sprite.groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict # Find all collided Sprite objects in both groups # Used to realize many to many collision detection # Parameters: # group1 group object of the first sprite object # group2 group object of the second sprite object # dokill1 bool value. If true, the collided sprite object will be removed from the first group in case of collision # dokill2 bool value. If true, the collided sprite object will be removed from the second group in case of collision # Collapsed is a function to judge collision. The parameters are two sprite objects, and you need to return bool value if you # The sprite object also has the rect attribute set in the example, which can not be passed # Returns a Sprite_dict object, similar to: # {<group1 Sprite(in 1 groups)>: [<group2 Sprite(in 1 groups)>]} # key is the group1 collision list, and value is the group2 collision list # The functions required for this example are listed above. For more usage methods, you can click the document link above to view the document
- pygame.font Used to load and render fonts
font.Font(filename, size) -> Font font.Font(object, size) -> Font # Loads a new font from a given file name or python file object # Parameters: # filename file path string, such as os.path.join('fonts', 'ziti.ttf') # object python file object # If the first parameter is passed to None, the default font will be used # Size integer type, font size # Returns a Font object font.Font.render(text, antialias, color, background=None) -> Surface # Create a new Surface on which the specified text is rendered. This method can only write one line of text without line feed. An empty string will throw an exception # Parameters: # Text text to display # antialias bool value. If true, the character will have smooth edges # Color font color RGB value # Background is used for text background color. If it is not passed, the background color is transparent # The functions required for this example are listed above. For more usage methods, you can click the document link above to view the document
>* * brief description of audio loading and required functions**
import os import sys import time import pygame # Screen width SCREEN_WIDTH = 500 # Screen height SCREEN_HEIGHT = 250 # Picture absolute path IMG_PATH = os.path.join(os.getcwd(), "img") # Mouse button identification MOUSE_MOVE = False # Long press the identification bit on the keyboard KEYDOWN = 0 # Background music path MUSIC_PATH = os.path.join(os.getcwd(), "sound") class HeroPlane(pygame.sprite.Sprite): def __init__(self): super(HeroPlane, self).__init__() self.image = pygame.image.load(os.path.join(IMG_PATH, "hero_show_1.png")) self.rect = self.image.get_rect() self.rect.x = 0 # Aircraft x-axis position self.rect.y = int(SCREEN_HEIGHT - self.rect.height) / 2 # Aircraft y-axis position self.is_running = True def move_level(self, level): # Prevent the aircraft from moving out of the screen and increase judgment if 0 <= level <= SCREEN_WIDTH - self.rect.width: self.rect.x = level elif level < 0: self.rect.x = 0 elif level > SCREEN_WIDTH - self.rect.width: self.rect.x = SCREEN_WIDTH - self.rect.width def move_vertical(self, vertical): if 0 <= vertical <= SCREEN_HEIGHT - self.rect.height: self.rect.y = vertical elif vertical < 0: self.rect.y = 0 elif vertical > SCREEN_HEIGHT - self.rect.height: self.rect.y = SCREEN_HEIGHT - self.rect.height class EnemyPlane(pygame.sprite.Sprite): def __init__(self): super(EnemyPlane, self).__init__() self.image = pygame.image.load(os.path.join(IMG_PATH, "mp_show_3.png")) self.rect = self.image.get_rect() self.rect = self.image.get_rect() self.rect.x = int(SCREEN_WIDTH - self.rect.width) # Aircraft x-axis position self.rect.y = int(SCREEN_HEIGHT - self.rect.height) / 2 # Aircraft y-axis position self.is_running = True def main(): pygame.init() # Initialize display module pygame.display.init() # create a window screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # Set window title pygame.display.set_caption("python Small demo Aircraft war") # Set window icon pygame.display.set_icon(pygame.image.load(os.path.join(IMG_PATH, "icon.jpg"))) # Load background picture background = pygame.image.load(os.path.join(IMG_PATH, "test_bj.png")) # Initialize hero hero = HeroPlane() # Initialize enemy aircraft enemy = EnemyPlane() # Load and play background music pygame.mixer.init() pygame.mixer.music.load(os.path.join(MUSIC_PATH, "game_music.ogg")) pygame.mixer.music.play(loops=-1) def event_check(): """ Event detection, here is a simple example return: """ global MOUSE_MOVE for event in pygame.event.get(): if event.type == pygame.QUIT: # Exit the program after receiving the exit event pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: MOUSE_MOVE = True elif event.type == pygame.MOUSEBUTTONUP: MOUSE_MOVE = False if MOUSE_MOVE: x, y = pygame.mouse.get_pos() hero.move_level(x) hero.move_vertical(y) # def event_check(): # """ # Event detection, here is a simple example # return: # """ # # Set the KEYDOWN flag bit. 0 indicates that the keyboard has been released, and 1, 2, 3 and 4 respectively represent ⬅,⬆,⬇,➡ # global KEYDOWN # # for event in pygame.event.get(): # if event.type == pygame.QUIT: # # Exit the program after receiving the exit event # pygame.quit() # sys.exit() # elif event.type == pygame.KEYDOWN: # if event.key == pygame.K_LEFT: # KEYDOWN = 1 # elif event.key == pygame.K_UP: # KEYDOWN = 2 # elif event.key == pygame.K_DOWN: # KEYDOWN = 3 # elif event.key == pygame.K_RIGHT: # KEYDOWN = 4 # elif event.type == pygame.KEYUP: # KEYDOWN = 0 # # if KEYDOWN: # if KEYDOWN == 1: # hero.move_level(hero.rect.x - 5) # elif KEYDOWN == 2: # hero.move_vertical(hero.rect.y - 5) # elif KEYDOWN == 3: # hero.move_vertical(hero.rect.y + 5) # else: # hero.move_level(hero.rect.x + 5) def update_hero(): screen.blit(hero.image, (hero.rect.x, hero.rect.y)) def update_enemy(): screen.blit(enemy.image, (enemy.rect.x, enemy.rect.y)) def check_crash(): is_crash = pygame.sprite.collide_rect(hero, enemy) if is_crash: # First show the plane explosion, and then write the game over prompt in the middle of the screen screen.blit(pygame.image.load(os.path.join(IMG_PATH, "ex_2.png")), (hero.rect.x, hero.rect.y)) screen.blit(pygame.image.load(os.path.join(IMG_PATH, "ex_2.png")), (enemy.rect.x, enemy.rect.y)) pygame.mixer.Sound(os.path.join(MUSIC_PATH, "enemy1_down.wav")).play() game_over = pygame.font.Font(None, 100) game_over = game_over.render("game over", True, (220, 20, 60)) screen.blit(game_over, [int(SCREEN_WIDTH / 2 - game_over.get_width() / 2), int(SCREEN_HEIGHT / 2)]) while True: # event detection event_check() # Draws a background picture onto the window screen.blit(background, (0, 0)) # Update the hero's position on the screen update_hero() # Update enemy position on screen update_enemy() # collision detection check_crash() # Update screen content pygame.display.update() time.sleep(0.02) if __name__ == "__main__": main()
Due to the restrictions of blog video conditions, there will be no effect here. Interested friends can pull down my code experience
Brief description of required functions
- pygame.mixer Used to load and play audio
mixer.init( frequency=44100, size=-16, channels=2, buffer=512, devicename=None, allowedchanges=AUDIO_ALLOW_FREQUENCY_CHANGE | AUDIO_ALLOW_CHANNELS_CHANGE ) -> None # Initialize the mixer module for sound loading and playback. You can override the default parameters to provide a specific audio mix # Parameters: # Frequency pyGame 2.0.0 +, range 44100-22050 # size indicates how many bits are used for each audio sample. If it is a negative value, the signed sample value will be used. An invalid value will trigger an exception, which can be 32 After 2.0.0 # channels specifies whether to use mono or stereo. 1 is mono, 2 is stereo, and can be 4 or 6 after 2.0.0 # buffer controls the number of internal samples used in the sound mixer mixer. The default value should be applicable to most cases # Allowedchanges when allowedchanges=0, the example will be converted at run time to match the content supported by the hardware. Allowedchanges also supports: # AUDIO_ALLOW_FREQUENCY_CHANGE # AUDIO_ALLOW_FORMAT_CHANGE # AUDIO_ALLOW_CHANNELS_CHANGE # AUDIO_ALLOW_ANY_CHANGE mixer.music.load(filename) -> None mixer.music.load(object) -> None # The music file and / or music file object will be loaded and ready to play. If the music has been played, the call will stop mixer.music.play(loops=0, start=0.0, fade_ms = 0) -> None # Play the loaded music stream. If it has been called during playback, it will be played again # Parameters: # loops is an optional integer parameter, which indicates the number of repeated playback. If it is set to - 1, it indicates infinite repetition # start optional floating-point number, indicating the position of the time when the music starts playing. The starting position depends on the music format # fade_ms is an optional integer parameter. When it is greater than 0, it is in the given fade_ Gradually increase the volume within Ms pygame.mixer.Sound(filename) -> Sound pygame.mixer.Sound(buffer) -> Sound # Create a new file object from a file or buffer pygame.mixer.Sound.play(loops=0, maxtime=0, fade_ms=0) -> Channel # Start playing sound on the available channels, which may cut off the playing sound if necessary # In this example, calling this method to produce an explosion sound effect does not affect the background music playing. # Parameters: # loops is an optional integer parameter, which indicates the number of repeated playback. If it is set to - 1, it indicates infinite repetition # When maxtime is greater than zero, playback stops at the given maxtime (in milliseconds) # fade_ms is an optional integer parameter. When it is greater than 0, it is in the given fade_ Gradually increase the volume within Ms # Returns the selected channel object # The functions required for this example are listed above. For more usage methods, you can click the document link above to view the document
python small demo complete example of aircraft war
On the above, I have demonstrated the modules and functions of using pygame to write a fighter plane. I also wrote an example, including the code used in this article to github. In the official account, we can get the source address, the picture material and the audio material in reply to the "aircraft war".