Python basic airplane battle host

1. Design heroes and bullets

Heroic needs

  1. After the game starts, the hero appears in the horizontal middle of the screen, 120 pixels from the bottom of the screen
  2. The hero fires three bullets in a row every 0.5 seconds
  3. The hero will not move by default. You need to use the left / right arrow keys to control the hero's movement in the horizontal direction

Bullet demand

  1. The bullet flew straight up from the hero's top
  2. After flying out of the screen, you need to remove it from the sprite group

    Hero

2. Create a hero

2.1 prepare for Heroes

  • Create a new Hero class in plane ﹣ sprites
  • Override the initialization method, specify the picture name directly, and set the initialization speed to 0
  • Set the hero's initial position
class Hero(GameSprite):
    """Hero Elf"""
 
    def __init__(self):
        # 1. Call the parent method and set image & speed
        super().__init__("./images/me1.png", 0)
        # 2. Set the hero's initial position
        self.rect.centerx = SCREEN_RECT.centerx
        self.rect.bottom = SCREEN_RECT.bottom - 120

2.2 drawing Heroes

  1. In "create" sprites, add hero sprite and hero sprite group
    • Later, we need to conduct collision detection and launch bullets against heroes
    • So heroes need to be individually defined as attributes
  2. In "upadte" sprites, let the hero sprite group call the update and draw methods

code implementation

Modify the "create" sprites method as follows:

#Create a hero's Sprite and Sprite group
        self.hero = Hero()
        self.hero_group = pygame.sprite.Group(self.hero)
//Modify the update sprites method as follows :
self.hero_group.update()
self.hero_group.draw(self.screen)
 

3. Move hero position

There are two ways to capture keyboard keys in pygame

  • The first way to judge event.type == pygame.KEYDOWN
  • The second way
  1. First, use pyGame. Key. Get Φ pressed() to return all key tuples

  2. Judge whether a key in the tuple is pressed through the keyboard constant -- if it is pressed, the corresponding value is 1
    What's the difference between the two ways?

  • The first way
elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
    print("Move to the right...")
  • The second way
# Use the method provided by the keyboard to obtain keyboard keys
keys_pressed = pygame.key.get_pressed()
# Determine the key index value 1 in the tuple
if keys_pressed[pygame.K_RIGHT]:
    print("Move to the right...")

conclusion

  • The first method, event.type, is that the user has to lift the key to calculate a key event. The operation flexibility will be greatly reduced
  • The second way is that the user can press and hold the direction key to move in a certain direction continuously, which makes the operation more flexible

3.1 mobile hero position

Rehearsal steps

  1. Override update method in Hero class
    • Stack with speed and hero rect.x
    • There is no need to call the parent method -- the parent method only implements simple vertical activities
  2. Add judgment condition in event hander
    • Right = > speed = 2
    • Left = > speed = - 2
    • Others = > speed = 0
#Use the method provided by the keyboard to obtain keyboard keys
keys_pressed = pygame.key.get_pressed()
# Judge the corresponding key index value in the tuple 1
if keys_pressed[pygame.K_RIGHT]:
    self.hero.speed = 3
elif keys_pressed[pygame.K_LEFT]:
    self.hero.speed = -3
else:
    self.hero.speed = 0

3.2 control the border of hero movement

right = x + width utilize right Property can easily set the sprite position on the right side
        # Control the hero's position
        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.right > SCREEN_RECT.right:
            self.rect.right = SCREEN_RECT.right

4. Firing bullets

4.1 add bullet event
pagame timer:

  1. Define timer constant ---- eventid
  2. In the initialization method, call the set timer method to set the timer event
  3. In the game cycle, listen for timer events
    code implementation

Define fire method in Hero
def fire(self):
print("fire bullets..." )
Define timer constant

#Hero shot event timer constant
HERO_FIRE_EVENT = pygame.USEREVENT + 1
 Let the hero fire a bullet in the event handler method
elif event.type == HERO_FIRE_EVENT:
    self.hero.fire()

4.2 defining bullets
Bullet -- bullet

  • Initialization method

    • Specify bullet picture
    • Initial speed = - 2 ---- the bullet needs to fly upward
  • Override the update() method

    • Determine whether to fly out of the screen, if so, delete from the sprite group
  • Defining bullets

  • Create a new Bullet in plane? Sprites and inherit it from GameSprites

  • Override the initialization method, specify the picture name directly, and set the initial speed

  • Override the update() method to determine that the bullet flies out of the screen and is removed from the sprite group

class Bullet(GameSprite):
    """Bullet spirit"""
 
    def __init__(self):
 
        # Call parent method, Set bullet picture, Set initial speed
        super().__init__("./images/bullet1.png", -2)
 
    def update(self):
 
        # Call parent method, Let the bullet fly in a vertical direction
        super().update()
 
        # Determine if the bullet flies out of the screen
        if self.rect.bottom < 0:
            self.kill()
 
    def __del__(self):
        print("The bullet was destroyed...")

4.3 firing bullets
Rehearsal steps

  1. Create bullet sprite group attribute in Hero's initialization method
  2. In the initialization function, create sprites and Sprite groups, and call the update and draw methods
  3. Implementing the fire() method
    • Create bullet Genie
    • Set the initial position -- directly above the hero
    • Add bullets to sprite group

code implementation

  • Initialization method
# 3. Create the sprite group of bullets
self.bullets = pygame.sprite.Group()
 modify fire() Method
    def fire(self):
        print("Bullet launch...")
 
        # 1. Create bullet Genie
        bullet = Bullet()
 
        # 2. Set sprite location
        bullet.rect.bottom = self.rect.y - 20
        bullet.rect.centerx = self.rect.centerx
 
        # 3. Add sprites to sprite group
        self.bullets.add(bullet)

Three bullets at a time

Modify the file() method
def fire(self):
print("fire bullets..." )

    for i in (0, 1, 2):
        # 1. Create a bullet Wizard
        bullet = Bullet()

        # 2. Set the location of spirit
        bullet.rect.bottom = self.rect.y - i*20
        bullet.rect.centerx = self.rect.centerx

        # 3. Add sprites to sprite group
        self.bullets.add(bullet)

5. De collision detection

  • pygame provides two very convenient methods for collision detection:

pygame.sprite.groupcollide()

  • Collision detection of all sprites in two sprite groups
pygame.sprite.groupcollide(group1, group2, dokill1, dokill2, collided = None) => Sprite_list
  • If dokill is set to True, the colliding sprite will be automatically removed

  • The collided parameter is a callback function used to calculate collisions

    • If not specified, each sprite must have a rect attribute

pygame.sprite.spritecollide()

  • Determine the collision between a sprite and a sprite in a specified sprite group
Sprite Collide (Sprite, group, dokill, collided = none) = > sprite_list
  • If dokill is set to True, the sprites in the specified sprite group that collide are automatically removed
  • The collided parameter is a callback function used to calculate collisions
    • If not specified, each sprite must have a rect attribute
  • Return to the list of sprites that collide with sprites in the sprite group
  1. Collision realization
    def __check_collide(self):

    # 1. Bullets destroy enemy aircraft
    pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)
    
    # 2. Enemy planes smash Heroes
    enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
    
    # Determine whether the list has content
    if len(enemies) > 0:
    
        # Let heroes die
        self.hero.kill()
    
        # End the game
        PlaneGame.__game_over()
    
Published 52 original articles, won praise 1, visited 618
Private letter follow

Tags: Attribute Mobile

Posted on Sat, 07 Mar 2020 06:09:59 -0500 by JoeDaStudd