Pick up where we left off, where we added the game frame, the background, and the movement of the player’s plane

The purpose of this tutorial is to achieve the creation of enemy aircraft, enemy aircraft movement, enemy aircraft and players after the collision, both destruction, rebirth and so on:

First prepare resources, the network can also be downloaded, I directly use the tutorial resources here, why (really good, find their own miserable)

Then not to say, directly on the code, basically every line of game code can be annotated and the end of the method are written in detail, if there is a description is not very correct place, you can comment (I am small dish chicken, please big guy light spray)

Enemy.py (enemy class, which contains enemy properties, running, resetting, etc.)

1. “Base class initialization”

Import PyGame from Random import * # small plane class # Pygame.sprite.Sprite is a class that implements sprites in PyGame. SmallEnemy(PyGame.sprite.Sprite) class SmallEnemy(PyGame.sprite.Sprite) Def __init__(self, bg_size): # def __init__(self, bg_size): SmallEnemy = pyGame.sprite; SmallEnemy = pyGame.sprite; SmallEnemy = pyGame.sprite; SmallEnemy = pyGame.sprite; SmallEnemy = pyGame.sprite; SmallEnemy = pyGame.sprite; If a subclass implements init(), it overrides the parent class, and since it inherits from the parent class, This function explicitly calls __init__() pygame.sprite.sprite.__init__ (self) # Enemy image self.image = Load ('images/enemy1.png').convert_alpha() # destruct self.destory_images = [] self.destory_images.extend([] pygame.image.load('images/enemy1_down1.png').convert_alpha(), pygame.image.load('images/enemy1_down2.png').convert_alpha(), pygame.image.load('images/enemy1_down3.png').convert_alpha(), Load ('images/enemy1_down4.png').convert_alpha()]) # self.width = bg_size[0] self.height = Bg_size [1] # get_rect() is a method for processing rectangular images, Self.rect = self.image.get_rect() # Randomly generates the position of the plane,randint(a,b) generates a<=n<=b, i.e., at the screen width, Self.rect. left = randint(0, self.width - self.rect.width) self.rect.top = randint(-5 * self.height, 0) # small enemy aircraft speed self.speed = 2 # Enemy aircraft alive state self.active = True # Aircraft collision detection, Def samll_enemy_move(self): self.mask = pygame.mask.from_surface(self.image) # def samll_enemy_move(self): # if the plane does not fly off the screen, the plane is moving downward. # if the plane does not fly off screen, the plane is moving downward. Self.rect. top += self.speed else: self.reset() # def reset(self): self.rect.top += self. Self. active = True self.active = True Self.rect. left = randint(0, self.width - self.rect.width) self.rect.top = randint(-5 * self.height, 0)Copy the code

The mian is an addition to the previous game, which calls the enemy class, generates small enemy planes, and then the enemy planes move, and if they collide with the player planes, both of them are destroyed, and the player’s life is reduced by one

main.py

Main knowledge points involved:

1. The pyGame.sprite.group () function creates a Sprite Group for unified management and the corresponding methods of the Group

2. Pygame.USEREVENT represents event 1, pyGame. And then capture the occurrence of the event through event.type == Invincible_event

3. Collision detection, pygame. Sprite. Spritecollide (Sprite, sprite_group, bool) : all elves will individually in a group of another individual spirit conflict detection

import pygame import sys import traceback from pygame.locals import * from random import * import myplane import enemy # Bg_size = width, height = 400, Screen = Pygame.display. Set_mode (bg_size) # Set window pygame.display. Set_caption (" Plane fight ") # Loading background image, normal image display effect with or without convert is the same, but with convert can convert format, Background = pygame.image.load("images/background.png").convert() BLACK = (0, 0, 0) GREEN = (0, 255, 0) RED = (255, 0, 0) WHITE = (255, 255, Def def small_enemies (small_enemies, enemiesGroup, num): for I in range(num): def def enemies (small_enemies, enemiesGroup, num): Smallenemy = enemy.smallEnemy (bg_size) # smallEnemy = enemy.smallEnemy (bg_size) Add add add # Group. Remove Remove # Group. Has determine the Sprite members # Group Group. Draw bitblock display # Group. Clear - Draw background # Group. Empty # Add this Group of enemy planes to the small plane attribute, equivalent to unified processing, Add (smallenemy) enemiesgroup.add (smallenemy) def main(): Clock = pygame.time.clock () # Create player plane me = myplane.myplane (bg_size) # create player plane me = myplane.myplane (bg_size) # The pygame.sprite.group () function can be used to create a Sprite Group. This Group contains all the properties of small, medium, and large planes, as long as it is used to handle collisions. # enemiesGroup = Pygame.sprite.group () # enemiesGroup = Pygame.sprite.group () Small_enemies = Pygame.sprite.group () add_small_enemies (small_enemies, enemiesGroup, Pygame.USEREVENT = event 1, PyGame.USEREVENT+1 = Event 2, etc. The invincible_event = PyGame.USEREVENT # pause the game, default is not paused paused = False # control the player plane picture switch, Switch_image = True # Switch delay = 100 # game score = 0 # Plane explosion picture subscript, in order of small enemy plane, medium enemy plane, large enemy plane, player plane explosion picture subscript, E1_destory_index = 0 e2_destory_index = 0 e3_destory_index = 0 me_destory_index = 0 RUNNING = True while e1_destory_index = 0 Running: # Get events for event in Pygame.event.get (): # End events trigger end operations if event.type == QUIT: Pygame.quit () sys.exit() # pygame.time.set_timer(Invincible_event, 3*1000) # means that the Invincible_event event will run in 3 seconds. If event. Type == Invincible_event: # Invincible = False Pygame.time.set_timer (Invincible_event, invincible_event, Key_pressed = Pygame.key.get_pressed () if key_pressed[K_w] or key_pressed[K_UP]: me.moveUp() if key_pressed[K_s] or key_pressed[K_DOWN]: me.moveDown() if key_pressed[K_a] or key_pressed[K_LEFT]: me.moveLeft() if key_pressed[K_d] or key_pressed[K_RIGHT]: Me. MoveRight () # Draw the background image above the screen, Screen. blit(background, (0, 0)) # if paused == False and life_num > 0: # if these are small_enemies, then we can do the same for ei in small_enemies: If ei. Active == True: Blit (ei.image, ei.rect) ei.samll_enemy_move() # Small enemy is destroyed (destroyed by player or collide with player) else: If not (delay % 4): if e1_destory_index == 0: Screen. blit(ei.destory_images[e1_destory_index], ei.rect) E1_destory_index = (e1_destory_index + 1) % 4 If e1_destory_index == 0: Ei. Reset () score += 1000 print(" ", score) # for collision detection, pygame. Sprite. Spritecollide (Sprite, sprite_group, bool) : all elves will individually in a group of another individual spirit conflict detection and conflict of the elves will be returned as a list. # the first argument is a single Sprite, the second argument is a group of sprites, and the third argument is a bool. If True, all conflicting sprites in the group will be removed. If False, no conflicting sprites will be removed. Pixels between two elves mask detect enemy_collide = pygame. Sprite. Spritecollide (me, enemiesGroup, False, pygame. Sprite. Collide_mask) # collision process, If enemy_collide and not me in the invincible state. # enemy_collide is a list of all enemy planes that have collided with each other and put their states as "destroyed" : If me. Active: # Draw the player plane on the screen,switch_image = whether to switch the image if switch_image: Screen.blit (me.image2, me.rect) # Change the flight image else: Screen.blit (me.image2, me.rect) # Change the flight image If not (delay % 4): if me_destory_index == 0: Screen. blit(me.destory_image[me_destory_index], me.rect) # Switch the subscript of the explosion image, Me_destory_index = (me_destory_index + 1) % 4 # If me_destory_index == 0 Life_num -= 1 # reset status me.reset() # Set invincible time to 3 seconds, after 3 seconds Pygame.time. set_timer: triggers an unbeatable time event, pyGame.time. set_timer: means that every time (here 3ms * 1000 = 3s), Pygame.time. set_timer(Invincible_event, 3 * 1000) delay -= 1 if delay == 0: Delay % 5 == 0 delay % 5 == 0 Switch_image = not switch_image # Update the entire Surface object to be displayed on the screen, display the contents of memory on the screen pygame.display.flip() Tick (60) if __name__ == "__main__": try: main() Print (" Game exit!" Traceback.print_exc () pygame.quit() traceback.print_exc() pygame.quit()Copy the code

Myplane.py from the previous one, there are no additional things added here, so paste it here too:

Import PyGame # Player plane class, PyGame. Sprite module contains a class named Sprite, which is a native of PyGame. class MyPlane(pygame.sprite.Sprite): def __init__(self, bg_size): # convert_alpha() Changes the pixel format of the image, Include alpha for each pixel, equivalent to making the image background transparent self.image1 = pygame.image.load('images/me1.png').convert_alpha() self.image2 = Pygame.image.load ('images/me2.png').convert_alpha() # Plane destroyed image save in digital form self.destory_image = [] self.destory_image.extend([] self.destory_image.extend([]  pygame.image.load('images/me_destroy_1.png').convert_alpha(), pygame.image.load('images/me_destroy_2.png').convert_alpha(), pygame.image.load('images/me_destroy_3.png').convert_alpha(), Load ('images/ me_Destroy_4.png ').convert_alpha()]) # define screen width self.width = bg_size[0] self.height = Bg_size [1] # get_rect() is a method for processing rectangular images, Self.rect = self.image1.get_rect() # The initial position of the plane,// is divisible, Left = (self.width - self.rect.width)//2 self.rect.top = self.height - self.rect.height MyPlaneSpeed = 10 self. Active = True self. Invincible = False Ignores the white background of the image and returns a Mask # from the specified Surface object for quick perfect collision detection. Mask can be accurate to 1 pixel level judgment. Set the transparent part of the Surface object to 1 and the opaque part to 0. Self. mask = pygame.mask.from_surface(self.image1) # def moveUp(self): If self.rect.top > 0: self.rect.top -= self.myplanespeed # else: Self.rect. top = 0 # def moveDown(self): If self.rect.bottom < self.height-60: Self. Rect. bottom += self. MyPlaneSpeed else: Def moveLeft(self): if self. Rect. left > 0: Self.rect. left -= self. MyPlaneSpeed else: self.rect.left = 0 # Def moveRight(self): if self.rect.right < self.width: self.rect.right += self.myPlaneSpeed else: Self.rect. right = self.width # def reset(self): Self. Active = True # Respawns invincible = True # Respawns invincible = True # Left = (self.width - self.rect.width) // 2 self.rect.top = self.height - self.rect.height - 60Copy the code