python-pygame realizes aircraft wars-4-obtaining supplies, launching enhanced bullets, and zooming in to clear the screen

python-pygame realizes aircraft wars-4-obtaining supplies, launching enhanced bullets, and zooming in to clear the screen

The effect of this step is to:

1. Added super bomb and enhanced bullet supply functions: as follows

2. After the user obtains the supply of super bombs and booster bullets, the bullets will be boosted first, and at the same time press the space bar to release the big move and clear the aircraft on the screen

First prepare the resources, they can also be downloaded from the Internet. The resources of the tutorials I use directly here, why are they?

In fact, through the first few steps, the basic framework of the entire game is almost the same, that is, add a new function to the original framework. Here is a supply.py: mainly the control of the supply, including the movement and resetting of the supply. In fact, the writing method is all almost

import pygame from random import * # Bullet Supply class Bullet_Supply(pygame.sprite.Sprite): def __init__(self, bg_size): pygame.sprite.Sprite.__init__(self) # Picture of bullet supply self.image = pygame.image.load('images/bullet_supply.png').convert_alpha() # Define screen width and height self.width = bg_size[0] self.height = bg_size[1] # get_rect() is a method for processing rectangular images. The return value contains the attributes of the rectangle. Here, the position of the aircraft image 1 is returned, and the width and height of the image can be obtained. self.rect = self.image.get_rect() # Random bullet supply position, randint(a,b) generates a<=n<=b, which is randomly generated under the width of the screen and 2 times the height self.rect.left = randint(0, self.width-self.rect.width) self.rect.top = randint(-2 * self.height, 0) # The survival status of the supply, that is, whether it is displayed and can it be touched self.active = False # Supply down state self.speed = 5 # Bullet Supply Movement def move(self): # Not yet down to the bottom if self.rect.top <self.height: # Then continue to move down self.rect.top += self.speed else: # After falling to the bottom, the state becomes inactive self.active = False # Bullet supply reset def reset(self): # State reset self.active = True # Random bullet supply position, randint(a,b) generates a<=n<=b, which is randomly generated under the width of the screen and 2 times the height self.rect.left = randint(0, self.width-self.rect.width) self.rect.top = randint(-2 * self.height, 0) # Super bomb supply class Bomb_Supply(pygame.sprite.Sprite): def __init__(self, bg_size): pygame.sprite.Sprite.__init__(self) # Super bomb picture self.image = pygame.image.load('images/bomb_supply.png').convert_alpha() # Define screen width and height self.width = bg_size[0] self.height = bg_size[1] # get_rect() is a method for processing rectangular images. The return value contains the attributes of the rectangle. Here, the position of the aircraft image 1 is returned, and the width and height of the image can be obtained. self.rect = self.image.get_rect() # The location of the super bomb supply, randint(a,b) will generate a<=n<=b, which is randomly generated under the screen width and 2 times the height self.rect.left = randint(0, self.width-self.rect.width) self.rect.top = randint(-2 * self.height, 0) # The survival status of the supply, that is, whether it is displayed and can it be touched self.active = False # Supply down state self.speed = 5 # Super bomb mobile def move(self): # Not yet down to the bottom if self.rect.top <self.height: # Then continue to move down self.rect.top += self.speed else: # After falling to the bottom, the state becomes inactive self.active = False # Bullet supply reset def reset(self): # State reset self.active = True # The location of the super bomb supply, randint(a,b) will generate a<=n<=b, which is randomly generated under the screen width and 2 times the height self.rect.left = randint(0, self.width-self.rect.width) self.rect.top = randint(-2 * self.height, 0) Copy code

main.py: The rendering of super bullets is added on the basis of the previous, and the bullet timer event and replenishment time event are also set.

1. The function is reflected in the provision of a supply every 8 seconds, randomly selected (super bomb/enhanced bullet)

2. Aircraft pick up and supply (processed by collision mechanism)

3. Pick up the enhanced bullet, the bullet changes, and the enhanced bullet lasts for 4 seconds

4. Pick up the super bombs, the number of super bombs changes (up to 3), and put the super bomb in the blank space at the same time, write as much as possible on the clear screen comment, and the writing feels a bit messy

import pygame import sys import traceback from pygame.locals import * from random import * import myplane import enemy import bullet import supply # Initialization pygame.init() # Set window size bg_size = width, height = 400, 700 # actually a tuple screen = pygame.display.set_mode(bg_size) # set window pygame.display.set_caption("Aircraft War") # Window title # Load the background image, the display effect of the ordinary image is the same with or without convert, but using convert can convert the format and improve the speed of blit background = pygame.image.load("images/background.png").convert() # Set the corresponding values of black, green, red, and hundreds of colors, which will be used later BLACK = (0, 0, 0) GREEN = (0, 255, 0) RED = (255, 0, 0) WHITE = (255, 255, 255) # Generate enemy small aircraft def add_small_enemy(small_enemies, enemiesGroup, num): for i in range(num): smallenemy = enemy.SmallEnemy(bg_size) # Wizard group to achieve multiple images, very suitable for processing the list of sprites, there are methods of adding, removing, drawing, updating, etc. # Group.sprites sprite group # Group.copy Copy # Group.add add # Group.remove remove # Group.has Determine the members of the wizard group # Group.update update # Group.draw Bit block display # Group.clear-draw background # Group.empty empty # Add small aircraft attributes to this group of enemy aircraft, which is equivalent to unified processing and unified assignment small_enemies.add(smallenemy) enemiesGroup.add(smallenemy) def main(): # Create a clock object (you can control the game loop frequency) clock = pygame.time.Clock() # Generate player aircraft me = myplane.MyPlane(bg_size) # Store all enemy aircraft, this aircraft group contains various attributes of small aircraft, medium aircraft, and large aircraft, as long as it is used to deal with collisions # When there are a large number of entities in the program, operating these entities will be quite troublesome # Use the pygame.sprite.Group() function to create a sprite group for unified management. Here, an enemy unit is created enemiesGroup = pygame.sprite.Group() # Generate local small airplanes, and enemy small airplanes are also a group for unified processing small_enemies = pygame.sprite.Group() add_small_enemy(small_enemies, enemiesGroup, 15) # Generate ordinary bullets, here is a loop of four bullets bullet1s = [] # Mark which bullet happened bullet1s_index = 0 # Number of bullets bullet1_num = 4 for i in range(bullet1_num): # Send the position of the player's plane to the bullet bullet1s.append(bullet.Bullet1(me.rect.midtop)) # Generate enhanced bullets, here is a cycle of eight bullets, four on each side bulletspro = [] # Mark which bullet happened bulletspro_index = 0 # Number of bullets bulletspro_num = 8 # Press four bullets on the left and right sides, and//2 means divisible, and the practicality of/2 is the same for i in range(bulletspro_num//2): # Here (me.rect.centerx-33, me.rect.centery) refers to the position of the tuple, centerx represents the x-axis, centery represents the y-axis bulletspro.append(bullet.Bullet2((me.rect.centerx-33, me.rect.centery))) bulletspro.append(bullet.Bullet2((me.rect.centerx + 33, me.rect.centery))) # Initialize enhanced bullet supply, super bomb supply bullet_supply = supply.Bullet_Supply(bg_size) bomb_supply = supply.Bomb_Supply(bg_size) # Set the invincible time event, pygame.USEREVENT represents event 1, pygame.USEREVENT+1 represents event 2, and so on, here is equivalent to defining an event invincible_event = pygame.USEREVENT # Set replenishment time event bullet_time_supply = pygame.USEREVENT + 1 # Set to strengthen the bullet timer event, that is, to strengthen the bullet buff continuous event bulletpro_time = pygame.USEREVENT + 2 # Set a timer and distribute supplies every 8 seconds pygame.time.set_timer(bullet_time_supply, 8 * 1000) # Mark whether to use super bullets is_double_bullet = False # Player three lives life_num = 3 # The number of players with super bombs bomb_num = 3 # The game is paused, the default is not paused paused = False # Control the player s aircraft picture switch to show the effect of the sudden sudden switch_image = True # Switch delay delay = 100 # Game score score = 0 # The subscripts of the pictures of the airplane explosion, followed by the subscripts of the pictures of the small enemy aircraft, medium enemy aircraft, large enemy aircraft, and the player s aircraft. Switch the subscripts to change the explosion picture e1_destory_index = 0 e2_destory_index = 0 e3_destory_index = 0 me_destory_index = 0 running = True while running: # Get event for event in pygame.event.get(): # End event triggers end operation if event.type == QUIT: pygame.quit() sys.exit() # When the collision was triggered, pygame.time.set_timer(invincible_event, 3*1000) was written # Means that the invincible_event event will be executed after 3 seconds. The invincible_event event is captured here. After execution, the timer will be cancelled to prevent repeated execution of the loop and wait for the next trigger elif event.type == invincible_event: # Remove invincibility me.invincible = False pygame.time.set_timer(invincible_event, 0) # Trigger supply event elif event.type == bullet_time_supply: # Randomly make a judgment, if it is True, send out enhanced bullet supplies if choice([True, False]): # Issue enhanced bullet supplies bullet_supply.reset() else: # Distribute super bomb supplies bomb_supply.reset() # Strengthen the bullet buff expiration event elif event.type == bulletpro_time: # Bullet switch to normal bullet is_double_bullet = False # The event stops the loop and waits for the next trigger pygame.time.set_timer(bulletpro_time, 0) # Capture key operation elif event.type == KEYDOWN: # If the space is pressed, the ultimate move is triggered, and the super bomb clears the aircraft on the screen if event.key == K_SPACE: if bomb_num> 0: bomb_num -= 1 # Determine whether all enemy aircraft present are in the game screen for ei in enemiesGroup: if ei.rect.bottom> 0: ei.active = False # Detect user keyboard operations, respectively up, down, left, and right 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 a background image on the screen and specify the position screen.blit(background, (0, 0)) # Draw various elements such as bullet supply, bomb supply, enemy aircraft, player aircraft, etc. # Not paused and life is greater than 0 if paused == False and life_num> 0: # Draw the bullet supply, if the bullet supply status is true, it will trigger the bullet supply operation if bullet_supply.active: # The bullet starts to move, and the bullet supply picture is rendered bullet_supply.move() screen.blit(bullet_supply.image, bullet_supply.rect) # If it collides with the player s aircraft during the fall, it means that the player s aircraft has picked up the bullet supply # pygame.sprite.collide_mask: pixel mask detection between two sprites, receiving two sprites as parameters, and the return value is a bool variable if pygame.sprite.collide_mask(bullet_supply, me): # Change the supply status of bullets, including hiding and no longer being picked up bullet_supply.active = False # Aircraft bullets changed to reinforced bullets is_double_bullet = True # Set to strengthen the bullet buff lasting event, here lasts 4s pygame.time.set_timer(bulletpro_time, 4 * 1000) # Draw the super bomb supply, if the super bomb status is true, it will trigger the super bomb supply operation if bomb_supply.active: # The super bomb replenishment starts to move, and the replenishment picture is rendered bomb_supply.move() screen.blit(bomb_supply.image, bomb_supply.rect) # Player's aircraft picked up to supply if pygame.sprite.collide_mask(bomb_supply, me): # Change the supply status, including hiding and no longer picking up bomb_supply.active = False # Determine the number of super bombs, which cannot be greater than 3 if bomb_num <3: bomb_num += 1 print("Bomb number:", bomb_num) # Draw a small enemy aircraft. This is because the small aircraft group is defined above, and the aircraft group adds the attributes of the small aircraft (speed, position, etc.), and the aircraft is generated on the map at this time # If these aircraft are small enemy aircraft, they are dealt with together for ei in small_enemies: # The enemy plane is alive and has not been destroyed if ei.active == True: # Draw a small enemy plane, and the enemy plane starts to move screen.blit(ei.image, ei.rect) ei.samll_enemy_move() # The small enemy aircraft is destroyed (destructed by the player or collided with the player) else: # The delay% 4 set here means that the explosion screen is 4 frames (personal guess), which is understood as the explosion stay time, which can be set by yourself if not (delay% 4): # Used to play the explosion sound, only once per enemy aircraft if e1_destory_index == 0: print("Play the explosion sound of the enemy aircraft") # Draw the enemy plane impact explosion screen screen.blit(ei.destory_images[e1_destory_index], ei.rect) # Switch the exploded picture subscript to switch the exploded picture e1_destory_index = (e1_destory_index + 1)% 4 # An enemy plane that has experienced a round of explosions can be destroyed or reborn. It must be dealt with, otherwise it will continue to explode and explode # Here choose to rebirth if e1_destory_index == 0: ei.reset() score += 1000 print("score:", score) # Do collision detection, pygame.sprite.spritecollide(sprite,sprite_group,bool): All sprites in a group will perform collision detection on another single sprite one by one, and the sprites in conflict will be returned as a list. # The first parameter is a single sprite, the second parameter is a sprite group, and the third parameter is a bool value. The last parameter plays a big role. When True, all conflicting sprites in the group will be deleted; when False, conflicting sprites will not be deleted # The fourth parameter is: pixel mask detection between two sprites enemy_collide = pygame.sprite.spritecollide(me, enemiesGroup, False, pygame.sprite.collide_mask) # Collision processing, if the collision is not in an invincible state if enemy_collide and not me.invincible: # The player plane triggers the destruction state me.active = False # enemy_collide is a list that stores all enemy aircraft that collided with the player s aircraft, and then set the state of the colliding enemy aircraft to the destroyed state for ei in enemy_collide: ei.active = False # Draw the player's plane, if the plane is active if me.active: # Draw the player plane on the screen, switch_image is whether to switch the picture if switch_image: screen.blit(me.image1, me.rect) # Switch to the flight picture else: screen.blit(me.image2, me.rect) # Represents the plane was collided and the explosion event else: if not (delay% 4): # Used to play the explosion sound, only once per enemy aircraft if me_destory_index == 0: print("Player airplane explosion sound") # Draw the player impact explosion screen screen.blit(me.destory_image[me_destory_index], me.rect) # Switch the exploded picture subscript to switch the exploded picture me_destory_index = (me_destory_index + 1)% 4 # After the explosion screen is played, the plane is reborn if me_destory_index == 0: # Reduce one life, if you see 0, you will automatically skip the previous cycle life_num -= 1 # Reset status me.reset() # The invincibility time is set to 3 seconds, after 3 seconds, the invincibility time event is triggered, pygame.time.set_timer: is to perform some actions at regular intervals (here 3 milliseconds * 1000 = 3s) pygame.time.set_timer(invincible_event, 3 * 1000) # Fire a bullet every 10 units of time if not(delay% 10): # If it is a normal bullet if is_double_bullet == False: bullets = bullet1s # First stator bomb 0 position bullets[bullet1s_index].reset(me.rect.midtop) # Switch to the next bullet bullet1s_index = (bullet1s_index + 1)% bullet1_num # If it is a super bullet else: # Then the bullet is switched to a strengthened bullet bullets = bulletspro # Strengthen the bullet reset position from left to right, the logic is actually the same as the ordinary bullet, but the position is changed bullets[bulletspro_index].reset((me.rect.centerx-33, me.rect.centery)) bullets[bulletspro_index + 1].reset((me.rect.centerx + 33, me.rect.centery)) # Switch to the next set of bullets bulletspro_index = (bulletspro_index + 2)% bulletspro_num # Draw bullet for bul in bullets: if bul.active: # If the bullet is activated, it can be moved and drawn bul.move() screen.blit(bul.image, bul.rect) # The collision between the bullet and the enemy aircraft, the collision between the bullet and the enemy unit, under normal circumstances is actually a 1 to 1 collision enemy_hit = pygame.sprite.spritecollide(bul, enemiesGroup, False, pygame.sprite.collide_mask) # If there is an enemy plane hit by a bullet if enemy_hit: # The bullet that hits the enemy aircraft is first marked as inactive. The next time you cycle to this bullet, it will actually be reset and displayed again bul.active = False for ei in enemy_hit: ei.active = False delay -= 1 if delay == 0: delay = 100 # Switch the flying picture style every 5 frames if delay% 5 == 0: switch_image = not switch_image # Update the entire Surface object to be displayed on the screen, and display the contents of the memory on the screen pygame.display.flip() # Specify the cycle frequency through the clock object, cycle 60 times per second # Frame rate means that the program draws a picture on the screen every second clock.tick(60) if __name__ == "__main__": try: main() # Service exits normally except SystemExit: print("The game exits normally!") # pass Ignore the error and continue to run down, in fact, here and exited pass # Service has other exceptions except: # Print the error directly traceback.print_exc() pygame.quit() Copy code

bullet.py: Mainly the control of bullets, including the various attributes of bullets and the resetting of bullets. Enhanced bullets are added. The writing method varies

import pygame # Bullet 1 class Bullet1(pygame.sprite.Sprite): # The position here is actually the position of the player s plane, because the position of the plane changes, and all bullets also change def __init__(self, position): # Here is still the same, "Initialization of the base class", see the introduction in enemy.py for details pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('images/bullet1.png').convert_alpha() # get_rect() is a method for processing rectangular images, the return value contains the attributes of the rectangle, here the position of the bullet is returned, and the width and height of the image can be obtained self.rect = self.image.get_rect() # Define the position of the bullet self.rect.left = position[0] self.rect.top = position[1] # Determine whether the bullet is activated self.active = True # Bullet speed self.bulletSpeed = 12 # Collision detection, will ignore the white background part of the picture self.mask = pygame.mask.from_surface(self.image) # Bullet Move def move(self): self.rect.top -= self.bulletSpeed # Beyond the screen, it is defined as inactive and killed at the same time, otherwise resources will be consumed if self.rect.top <0: self.active = False # Bullet reset def reset(self, position): self.active = True self.rect.left = position[0] self.rect.top = position[1] # Bullet 2, which means to strengthen the bullet class Bullet2(pygame.sprite.Sprite): # The position here is actually the position of the player s airplane, because the position of the airplane changes, so all the reinforced bullets also change def __init__(self, position): pygame.sprite.Sprite.__init__(self) # Strengthen the bullet picture self.image = pygame.image.load('images/bullet2.png').convert_alpha() # get_rect() is a method for processing rectangular images, the return value contains the attributes of the rectangle, here the position of the bullet is returned, and the width and height of the image can be obtained self.rect = self.image.get_rect() # Define the position of the bullet self.rect.left = position[0] self.rect.top = position[1] # Determine whether the bullet is activated self.active = True # Strengthen bullet speed self.bulletSpeed = 14 # Collision detection, will ignore the white background part of the picture self.mask = pygame.mask.from_surface(self.image) # Strengthen bullet movement def move(self): self.rect.top -= self.bulletSpeed # Beyond the screen, defined as inactive if self.rect.top <0: self.active = False # Bullet reset def reset(self, position): self.active = True self.rect.left = position[0] self.rect.top = position[1] Copy code

myplane.py: Mainly controls the player s aircraft, including the various attributes of the player s game aircraft, the movement of the aircraft up and down, and the rebirth of the aircraft.

I won t put it up here, it s all in the first few steps

The effect of this step is to control the movement of the aircraft, shoot and destroy the enemy aircraft.