[Python] Python game--Airplane battle

1. Preface Today is the fourth day of the lunar new year. The Spring Festival when we are comfortable lying down at home is over. We are also startin...
1. Preface
2. Compiling software and python libraries used
3. Game Operations and Rules
4. Game Running Test (screenshot)
5. Details of the overall structure of the game and the py files of the game
6. Source code and video tutorials

1. Preface

Today is the fourth day of the lunar new year. The Spring Festival when we are comfortable lying down at home is over. We are also starting to study and work hard.To add another word, the virus epidemic this Spring Festival has really made people panic. I am here to fuel the country and Wuhan, and salute the front-line workers, hoping to end the epidemic soon.
Okay, there's a little bit of off-topic talk, so here's how to start a little game plane fight written by python.Anxious buddies can go directly to the bottom of the blog to find links. I've provided you code source and development documentation. Ha-ha.

2. Compiling software and python libraries used

1. Compile software

I'm using PyCharm, the compiler software that's commonly used to write large python projects, and it's generally better.You can download it on the Internet by yourself, of course, generally good software needs to be paid.Ha-ha, PyCharm is no exception. I remember that this software has a 30-day free experience period, but the hardcore farmers who often crack the software usually go online to find the secret key to crack.

2.python Library

Here are some of the main uses:
(1) pygame Library
Pygame is a cross-platform Pyth, authored by Pete Shinners, under the GNU Lesser General Public License.Pygame contains images and sounds.Based on SDL, real-time video game development is allowed without the constraints of low-level languages such as machine language and assembly language.Based on this assumption, all required game functions and concepts (mainly in terms of images) are completely simplified into the game logic itself, and all resource structures can be provided by advanced languages such as Python.
(2) random library
Random is a library of random numbers, which are random number generators. Random produces pseudo-random numbers or sequence values calculated using a complex method, so a different seed value is required for each operation.Different seed values result in different sequence values.
(3) time Library
The time library is the standard library for processing time in Python. It is used to express computer time, provide functions to get system time and format output, provide precise system-level timing, and can also be used for program performance analysis.
(4) sys Library
Sys.exit ([arg]) is used to exit a program, sys.exit(n) exits the program, and exit(0) normally exits.This is achieved by throwing a SystemExit exception, so the cleanup operation try specified in the final statement's clause is followed, and the outer exit attempt can be intercepted.The optional parameter arg can be an integer that gives an exit status (default is zero) or other type of object.If it is an integer, zero is considered a Successful Termination, and any non-zero value, etc., is considered an Abnormal Termination.

3. Game Operations and Rules

1. Game Operations and Rules
(1) To shoot an enemy aircraft by controlling the direction of the aircraft's movement with the keyboard keys up, down, left and right or WASD.
(2) Release the missiles through the keyboard space keys, and defeat all the enemy planes in the game interface. There are initially three missiles. During the game, missile replenishment will occur to supplement the missiles, and a maximum of three can be obtained.
(3) Different scores are obtained according to the level of defeating the enemy aircraft. The scores are accumulated and correspond to five difficulty levels. The higher the score, the more difficult it is.
(4) In the course of moving shooting, an enemy aircraft cannot be collided. Each time an enemy aircraft is collided, one life is lost. There are three lives lost in the aircraft. After three lives are lost, the game ends.
2. Overall Game Design


4. Game Running Test (screenshot)

Game Run Screenshot

End of Game Screenshot


5. Details of the overall structure of the game and the py files of the game

1. Overall Game Architecture

(1) Define a display window (480*700px); control aircraft bullet speed, enemy aircraft refresh time and replenishment refresh time according to frame number;
(2) Define player controllers, enemy aircraft, bullets and supply classes, and display player controllers, enemy aircraft, scores, number of missiles, number of lives, supply and pause keys in windows;
(3) Define the game cycle;
(4) Define the movement of the player controller and the trigger of the missile, and control the movement of the aircraft and trigger the effect of the missile by detecting the keyboard input;
(5) Examine the end of the game and show the game's scoring, highest score, restart and exit options.

2. Game py files Main.py file: The main function file used to run the game.The rest of the files described below are import ed as packages for the main.py file.

(1) Initialize the main game interface

#pygame initialization pygame.init() pygame.mixer.init() #Set the background size (according to the size of the background picture) bg_size = width, height = 480, 700 screen = pygame.display.set_mode(bg_size) pygame.display.set_caption('Airplane Battle') #Title #Initial number of aircraft,Can be modified directly enemy3_num = 12 enemy2_num = 8 enemy1_num = 2 #Load Background Picture background = pygame.image.load('images/background.jpg').convert_alpha()

(2) Define the main function to generate player controllers, enemy aircraft, and supplies.Statistics score and increase the difficulty of the game according to the score, there are five levels of difficulty, corresponding to 50, 200, 500, 1200 points to increase the number and speed of medium and small enemy aircraft.Pause the game and determine if it is over, and draw the end interface.

#Play background music, loop pygame.mixer.music.play(-1) #Generation Controller me = myplane.MyPlane(bg_size) # Generate enemy aircraft enemies = pygame.sprite.Group() # Generate large enemy aircraft big_enemies = pygame.sprite.Group() add_big_enemies(big_enemies, enemies, enemy3_num) # Generate medium enemy aircraft mid_enemies = pygame.sprite.Group() add_mid_enemies(mid_enemies, enemies, enemy2_num # Generate small enemy aircraft small_enemies = pygame.sprite.Group() add_small_enemies(small_enemies, enemies, enemy1_num) # Generate normal bullets bullet1 = [] bullet1_index = 0 BULLET1_NUM = 4 for i in range(BULLET1_NUM): bullet1.append(bullet.Bullet1(me.rect.midtop)) #Generate bullets in the center of the top of an aircraft # Generate Super Bomb bullet2 = [] bullet2_index = 0 BULLET2_NUM = 8 for i in range(BULLET2_NUM // 2): bullet2.append(bullet.Bullet2((me.rect.centerx - 33, me.rect.centery))) bullet2.append(bullet.Bullet2((me.rect.centerx + 30, me.rect.centery))) # For Delay delay = 100 clock = pygame.time.Clock() #Index of shot pictures e1_destroy_index = 0 e2_destroy_index = 0 e3_destroy_index = 0 me_destroy_index = 0 # Statistical Score score = 0 score_font = pygame.font.Font('font/MSYH.TTF', 36) # Whether to pause the game paused = False pause_nor_image = pygame.image.load('images/pause_nor.png').convert_alpha() pause_pressed_image = pygame.image.load('images/pause_pressed.png').convert_alpha() resume_nor_image = pygame.image.load('images/resume_nor.png').convert_alpha() resume_pressed_image = pygame.image.load('images/resume_pressed.png').convert_alpha() pause_rect = pause_nor_image.get_rect() pause_rect.left, pause_rect.top = width - pause_rect.width - 10, 10 pause_image = pause_nor_image # Difficulty level level = 1 # Bomb bomb_image = pygame.image.load('images/bomb.png').convert_alpha() bomb_rect = bomb_image.get_rect() bomb_font = pygame.font.Font('font/MSYH.TTF', 40) bomb_num = 3 # Number of Life life_image = pygame.image.load('images/life.png').convert_alpha() life_rect = life_image.get_rect() life_font = pygame.font.Font('font/MSYH.TTF', 40) life_num = 3 # each30Release a resupply pack in seconds bullet_supply = supply.Bullet_Supply(bg_size) bomb_supply = supply.Bomb_Supply(bg_size) life_supply = supply.Life_Supply(bg_size) SUPPLY_TIME = USEREVENT # Custom Timing Events pygame.time.set_timer(SUPPLY_TIME, 30 * 1000) # Super Bullet Timer DOUBLE_BULLET_TIME = USEREVENT + 1 # Whether to use super bullets is_double_bullet = False # Invincible Time Timer INVINCIBLE_TIME = USEREVENT + 2 # Prevent duplicate opening of log files recorded = False running = True play_fly_sound = False # Whether to play the sound of large enemy aircraft fly ing
myplane.py file: The player controller file, which defines the player controller class.

(1) Define the player controller class, inherit the sprite class from pygame, initialize the player controller, import the picture of the player controller, set the initial position of the game interface, set the speed, etc.

#Import Controller self.image = pygame.image.load('images/me1.png').convert_alpha() self.destroy_images = [] self.destroy_images.extend([\ pygame.image.load('images/me_destroy_1.png'),\ pygame.image.load('images/me_destroy_2.png'),\ pygame.image.load('images/me_destroy_3.png'),\ pygame.image.load('images/me_destroy_4.png'),]) #Get rect self.rect = self.image.get_rect() self.width, self.height = bg_size[0], bg_size[1] #Control machine initial position self.rect.left, self.rect.top = \ (self.width - self.rect.width) // 2, \ self.height - self.rect.height - 60 self.speed = 10 #Controller speed self.active = True self.invincible = False #Flag of invincibility self.mask = pygame.mask.from_surface(self.image) #Mark opaque portions of incoming pictures as mask s

(2) Define the function of the player's control to move from top to bottom (function in class).

def moveUp(self): #Go up if self.rect.top > 0: self.rect.top -= self.speed else: self.rect.top = 0 def moveDown(self): #Go Down if self.rect.bottom < self.height - 60: self.rect.top += self.speed else: self.rect.bottom = self.height - 60 def moveLeft(self): #Turn left if self.rect.left > 0: self.rect.left -= self.speed else: self.rect.left = 0 def moveRight(self): #Turn right if self.rect.right < self.width: self.rect.left += self.speed else: self.rect.right = self.width

(3) Reset the function to reinitialize the function (function in class) of the player's controller after the player loses a life on the plane.

def reset(self): self.rect.left, self.rect.top = \ (self.width - self.rect.width) // 2, \ self.height - self.rect.height - 60 self.active = True self.invincible = True
enemy.py file: An enemy aircraft file used to define large, medium, and small enemy aircraft classes.

(1) Define the SmallEnemy class, inherit pygame's sprite class, and initialize the small enemy.

self.image = pygame.image.load('images/enemy1.png').convert_alpha() self.active = True self.rect = self.image.get_rect() self.width, self.height = bg_size[0], bg_size[1] self.speed = 2 self.mask = pygame.mask.from_surface(self.image) #Set the rectangular size of the range a small enemy can reach self.rect.left, self.rect.top = \ randint(0, self.width - self.rect.width), \ randint(-5 * self.rect.height, 0)

(2) Define the small enemy aircraft movement function (function in class) and set its direction of movement.

#Set up enemy aircraft movement def move(self): if self.rect.top < self.height: self.rect.top += self.speed else: self.reset()

(3) Define the small enemy aircraft reset function (function in class) and reinitialize it.

def reset(self): self.active = True self.rect.left, self.rect.top = \ randint(0, self.width - self.rect.width), \ randint(-7 * self.rect.height, 0)

(4) Define the MidEnemy and the BigEnemy classes, which operate basically like the small enemy classes.

bullet.py file: A bullet file used to define ordinary and super bullet classes.

(1) Define the ordinary bullet class (Bullet1), initialize the ordinary bullet, import the picture of the ordinary bullet into the program, set the speed of the ordinary bullet, and so on.

self.image = pygame.image.load('images/bullet1.png').convert_alpha() self.rect = self.image.get_rect() self.rect.left, self.rect.top = position self.speed = 12 self.active = False self.mask = pygame.mask.from_surface(self.image)

(2) Define a normal bullet movement function (a function in a class) to control a point direction of the bullet.

def move(self): self.rect.top -= self.speed if self.rect.top < 0: self.active = False

(3) Define the normal bullet reset function (function in class) and reinitialize the normal bullet.

def reset(self, position): self.rect.left, self.rect.top = position self.active = True

(4) Define the super bullet class (Bullet2), inherit pygame's sprite class, and perform the same basic operations as ordinary bullet classes.

supply.py file: A replenishment file that defines missiles, super bullets, and life-replenishment classes.

(1) Define the super bullet replenishment class (Bullet_Supply), inherit pygame's sprite class, initialize super bullet replenishment, import pictures of super bullet replenishment into the program, set the replenishment drop speed, and so on.

self.image = pygame.image.load('images/bullet_supply.png').convert_alpha() self.rect = self.image.get_rect() self.width, self.height = bg_size[0], bg_size[1] self.rect.left, self.rect.bottom = randint(0, self.width - self.rect.width), -100 self.speed = 5 self.active = False self.mask = pygame.mask.from_surface(self.image)

(2) Define the super bullet replenishment movement function (function in class) and specify the direction of replenishment movement.

def move(self): if self.rect.top < self.height: self.rect.top += self.speed else: self.active = False

(3) Define reset functions (functions in classes) and reinitialize superbullet supplies.

def reset(self): self.active = True self.rect.left, self.rect.bottom = \ randint(0, self.width - self.rect.width), -100

(4) Define the Missile Replenishment Class (Bomb_Supply) and Life_Supply, which operate essentially like a superbullet class.

6. Source code and video tutorials

1. Source code links

Python Writes a Game - Airplane Warfare
My code is cheap and only needs one credit. Ha-ha.If you want to get it for free, you can praise the blog, pink me and trust me privately, haha.

2. Video tutorial links (basic tutorials help you understand)

Station B - Little Turtle Python Zero Basic Teaching Last Airplane Battle Game Writing

Why can't names be repeated Twelve original articles were published, 3 were praised, and 811 were visited Private letter follow

28 January 2020, 22:00 | Views: 4881

Add new comment

For adding a comment, please log in
or create account

0 comments