The enemy plane came out
target
- Use timer to add enemy aircraft
- Design Enemy class
01. Use timer to add enemy aircraft
Run the lesson preparation code and observe the occurrence law of enemy aircraft:
- After the game starts, an enemy plane will appear every 1 second
- Each enemy plane flies below the screen at different speeds
- The horizontal position of each enemy aircraft is also different
- When the enemy plane flies out from the bottom of the screen, it will not fly back to the screen
1.1 timer
- In pygame, you can use pygame time. set_ Timer() to add a timer
- The so-called timer is to perform some actions at regular intervals
set_timer(eventid, milliseconds) -> None
- set_timer can create an event
- This event can be captured in the event listening method of the game loop
- The event code of the first parameter needs to be based on the constant pyGame Userevent to specify
- USEREVENT is an integer. Additional events can be specified with USEREVENT + 1, and so on
- The second parameter is the millisecond value of the event trigger interval
Listening for timer events
- Via pyGame event. Get() can get a list of all events at the current time
- Traverse the list and determine event Whether type is equal to eventid. If it is equal, it indicates that the timer event occurs
1.2 define and listen for timer events for creating enemy aircraft
The timer routine of pygame is very fixed:
- Define timer constant - eventid
- In the initialization method, call set_ The timer method sets the timer event
- In the game loop, listen for timer events
1) Define events
- In plane_ sprites. The top of Py defines event constants
# Timer event constant of enemy aircraft CREATE_ENEMY_EVENT = pygame.USEREVENT
- Create user events in the initialization method of PlaneGame
# 4. Set timer events - create one enemy aircraft per second pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)
2) Listen for timer events
- In__ event_ Add the following code to the handler method:
def __event_handler(self): for event in pygame.event.get(): # Determine whether to exit the game if event.type == pygame.QUIT: PlaneGame.__game_over() elif event.type == CREATE_ENEMY_EVENT: print("The enemy plane came out...")
02. Design Enemy class
- After the game starts, an enemy plane will appear every 1 second
- Each enemy plane flies below the screen at different speeds
- The horizontal position of each enemy aircraft is also different
- When the enemy plane flies out from the bottom of the screen, it will not fly back to the screen
- Initialization method
- Specify enemy picture
- Initial position and initial speed of random enemy aircraft
- Override the update() method
- Judge whether to fly out of the screen. If so, delete it from the wizard group
2.1 preparation of enemy aircraft
- In plane_sprites new Enemy inherited from GameSprite
- Override the initialization method and directly specify the picture name
- The designation of random speed and random position is not realized temporarily
- Rewrite the update method to determine whether to fly out of the screen
class Enemy(GameSprite): """Enemy spirit""" def __init__(self): # 1. Call the parent method, create the enemy wizard, and specify the image of the enemy super().__init__("./images/enemy1.png") # 2. Set the random initial speed of the enemy aircraft # 3. Set the random initial position of the enemy aircraft def update(self): # 1. Call the parent method to make the enemy plane move in the vertical direction super().update() # 2. Judge whether to fly out of the screen. If so, you need to delete the enemy aircraft from the wizard group if self.rect.y >= SCREEN_RECT.height: print("The enemy plane flew out of the screen...")
2.2 create enemy aircraft
Drill steps
- In__ create_sprites, add enemy plane sprite group
- The enemy aircraft is created regularly, so it is not necessary to create the enemy aircraft in the initialization method
- In__ event_handler, create the enemy aircraft and add it to the wizard group
- Call the add method of the sprite group to add sprites to the sprite group
- In__ update_sprites, let the enemy plane wizard group call the update and draw methods
Drill code
- Modify plan_ Main__ create_sprites method
# Enemy unit self.enemy_group = pygame.sprite.Group()
- Modify plan_ Main__ update_sprites method
self.enemy_group.update() self.enemy_group.draw(self.screen)
- Enemy aircraft appear regularly
elif event.type == CREATE_ENEMY_EVENT: self.enemy_group.add(Enemy())
2.3 random enemy aircraft position and speed
1) Import module
- When importing modules, it is recommended to import them in the following order
1. Official standard module import 2. Third party module import 3. Application module import
- Modify plan_ sprites. Py increase the import of random
import random
2) Random location
Use pyGame The bottom attribute provided by rect is convenient when specifying the initial position of the enemy aircraft
- bottom = y + height
- y = bottom - height
3) Code implementation
- Modify the initialization method to randomly the speed and position of the enemy aircraft
def __init__(self): # 1. Call the parent method, create the enemy wizard, and specify the image of the enemy super().__init__("./images/enemy1.png") # 2. Set the random initial speed of the enemy aircraft 1 ~ 3 self.speed = random.randint(1, 3) # 3. Set the random initial position of the enemy aircraft self.rect.bottom = 0 max_x = SCREEN_RECT.width - self.rect.width self.rect.x = random.randint(0, max_x)
2.4 remove the screen and destroy the enemy aircraft
- After the enemy plane moves out of the screen, if it does not hit the hero, the historical mission of the enemy plane has ended
- It needs to be deleted from the enemy unit, otherwise it will cause a waste of memory
Detect the destruction of enemy aircraft
- __ del__ The built-in method is called before the object is destroyed, and can be used to determine whether the object is destroyed in development.
def __del__(self): print("The enemy plane hung up %s" % self.rect)
code implementation
- Judge whether the enemy plane flies out of the screen. If so, call the kill() method to delete it from all groups
def update(self): super().update() # Judge whether the enemy aircraft moves out of the screen if self.rect.y >= SCREEN_RECT.height: # Remove sprites from all groups self.kill()