SoFunction
Updated on 2024-10-29

python3 implementation of a simple airplane wars

In this article, we share the example of python3 to achieve a simple airplane war specific code for your reference, the specific content is as follows

The game is divided into two parts:1. Main program 2. Game tools

Main program implementation:Game Loop, Event Listening, Graphics Drawing, Position Update, Collision Detection

Game Tools:Encapsulated background sprites, bullet sprites, hero sprites, enemy aircraft sprites

Development Environment:pycharm 2018,python3 ,pygame

Rendering:

Catalog structure:

Code:

plane_main.py

# coding=utf8
"""
The main game program
"""
# System modules
import random
# Third-party modules
import pygame
# Customized modules
from plane_sprites import * # Import all members of the module
 
 
class PlaneGame(object):
 """
 The main game program
 """
 
 def __init__(self):
 """
 Game Initialization
 """
 # 1. Create a game window
  = .set_mode(SCREEN_RECT.size)
 # 2. Create a game clock
  = ()
 # 3. Create sprites and sprite groups
 self.__create_sprites()
 # 4. Setting a timer event to create an enemy plane
 .set_timer(CREATE_ENEMY_EVENT, 100)
 # 5. Timer for firing bullets
 .set_timer(HERO_FIRE_EVENT, 500)
 
 def __create_sprites(self):
 """
 Creating a game sprite
 :return.
 """
 # 1. Creating background sprites and sprite groups
 bg1 = Backgroud()
 bg2 = Backgroud(True)
 self.back_group = (bg1, bg2)
 
 # 2. Creating Hero Sprites
  = Hero()
 self.hero_group = ()
 
 # 3. Creating enemy spritesets
 self.enemy_group = ()
 
 def start_game(self):
 """
 Start the game loop
 :return.
 """
 print("Start the game.")
 while True:
  # 1. Setting the refresh rate of the game screen
  (FRAME_PRE_SEC)
  # 2. Game Event Listening
  self.__event_handler()
  # 3. sprite collision detection
  self.check_collide()
  # 4. Update and draw sprite sets
  self.update_sprites()
  # 5. Updated display images
  ()
 
 def __event_handler(self):
 """
 Event Listener Handling
 :return.
 """
 for event in ():
  # Determine whether to quit the game
  if  == :
  PlaneGame.__game_over()
  elif  == CREATE_ENEMY_EVENT:
  print("Enemy planes out.")
  # 1. Create enemy sprites
  enemy = Enemy()
  # 2. Add enemy sprites to the sprite group
  self.enemy_group.add(enemy)
  elif  == :
  keys_pressed = .get_pressed()
  if keys_pressed[pygame.K_RIGHT]:
    = 1
  elif keys_pressed[pygame.K_LEFT]:
    = -1
  else:
    = 0
  elif  == :
  # 1. Button up not moving.
   = 0
 
  elif  == HERO_FIRE_EVENT:
  # Heroes firing bullets
  ()
  else:
  print()
 
 def check_collide(self):
 """
 Elf collision detection
 :return.
 """
 # 1. Bullets destroy enemy aircraft
 (, self.enemy_group, True, True)
 
 # 2. Enemy planes crashing into heroes
 """
 enemies = (, self.enemy_group, True)
 if len(enemies) > 0:
  ()
  PlaneGame.__game_over()
 """
 
 def update_sprites(self):
 """
 Update the location of the sprite
 :return.
 """
 # Update location
 self.back_group.update()
 self.hero_group.update()
 self.enemy_group.update()
 ()
 # Drawing graphics to the screen
 self.back_group.draw()
 self.hero_group.draw()
 self.enemy_group.draw()
 ()
 
 @staticmethod
 def __game_over():
 """
 Game over handling
 :return.
 """
 ()
 exit()
 
 
if __name__ == "__main__": # Module built-in attribute __name__ defaults to "__main__", mainly for testing purposes.
 # 1. Create a game object
 game = PlaneGame()
 # 2. Start the game
 game.start_game()

plane_sprites.py

# coding=utf8
"""
Game Genie
"""
# System modules
import random
# Third-party modules
import pygame
# Customized modules
from plane_sprites import * # Import all members of the module
 
# Game constants, there is no such thing as a constant in python, it is generally considered to be a constant if all the letters are capitalized.
SCREEN_RECT = (0, 0, 480, 700) # Game screen size settings
FRAME_PRE_SEC = 60 # Set the refresh rate of the game screen
# Path to the game image
BACKGROUND_IMAGE_NAME = "./images/"
HERO_IMAGE_NAME = "./images/"
ENEMY_IMAGE_NAME = "./images/"
BULLET_IMAGE_NAME = "./images/"
 
# Create timers
CREATE_ENEMY_EVENT = 
HERO_FIRE_EVENT =  + 1
 
 
class GameSprites():
 """
 Airplane Wars Game Sprites Base Class
 """
 
 def __init__(self, image_name, speed=1):
 # Call the initialization method of the parent class
 super().__init__()
 # Load images into memory
  = (image_name)
 # Get the initial position of the image
  = .get_rect()
  = speed
 
 def update(self, *args):
 # Move vertically down
  += 
 
 
class Backgroud(GameSprites):
 """
 Game Background Sprites
 """
 
 def __init__(self, is_alt=False):
 # 1. Call the parent class to create the sprite
 super().__init__(BACKGROUND_IMAGE_NAME)
 # 2. Determine if it's at the top of the screen
 if is_alt:
   = -
 
 def update(self):
 # 1. Call the parent class implementation
 super().update()
 # 2. Determine whether the background is flying out of the screen, if so set the background to the top of the screen.
 if  >= SCREEN_RECT.height:
   = -
 
 
class Hero(GameSprites):
 """
 Game Hero Wizard
 """
 
 def __init__(self):
 # 1. Call the parent class to set the image and speed
 super().__init__(HERO_IMAGE_NAME, 0)
 
 # 2. Set the initial position of the hero
  = SCREEN_RECT.centerx
  = SCREEN_RECT.bottom - 120
 
 # 3. Create a bullet sprite group
  = ()
 
 def update(self):
 # 1. Heroes move horizontally
  += 
 
 # 2. Control the hero without flying off the screen
 if  < 0:
   = 0
 elif  > SCREEN_RECT.right:
   = SCREEN_RECT.right
 
 def fire(self):
 for i in (0, 1, 2):
  # 1. Create bullet sprites
  bullet = Bullet()
  # 2. Setting the sprite position
   =  - 20 * i
   = 
  # 3. Add to sprite group
  (bullet)
 
 
class Enemy(GameSprites):
 """
 The Enemy Elf
 """
 
 def __init__(self):
 super().__init__(ENEMY_IMAGE_NAME)
 # 1. Specify the initial speed of enemy aircraft.
  = (1, 3)
 # 2. Designate random locations for enemy aircraft
  = 0
 max_x = SCREEN_RECT.width - 
  = (0, max_x)
 
 def update(self):
 # 1. call the parent class method to keep flying vertically
 super().update()
 # 2. Determine if the plane is flying off the screen, and if so remove the enemy plane from the sprite set.
 if  >= SCREEN_RECT.height:
  # Auto-destruct, call __del()__ built-in methods
  ()
 
 def __del__(self):
 print("Enemy planes gone %s" % )
 
 
class Bullet(GameSprites):
 """
 The Bullet Wizard
 """
 
 def __init__(self):
 super().__init__(BULLET_IMAGE_NAME, -2)
  = ()
 
 def update(self):
 super().update()
 if  < 0:
  ()

    480*700

10*20

80*85

120*125

Game graphics, drawn at random, are for reference only.

This is the whole content of this article.