Implementation of enemy aircraft class in pygame research

Posted by nedpwolf on Sun, 02 Jan 2022 18:05:36 +0100

Several problems of enemy aircraft should be solved in fighter Games:

1. Self drawing and related attribute management (multiple types of fighters can be realized)

2. Self movement control (linear movement, left swing and right swing, S random change)

3. The effect of being hit and the HP of different types of enemy aircraft (it's boring to kill with one shot)

4. Management of fired bullets (random firing probability, initial position control of bullets, and automatic destruction of bullets beyond the scope of the screen to prevent unnecessary occupation of computing resources.)

First look at the overall framework

Then we take it apart paragraph by paragraph to see the specific implementation

1. Self drawing and related attribute management (multiple types of fighters can be realized)

class EnemySprite(pg.sprite.Sprite):
    # Enemy aircraft initialization
    def __init__(self, _enemytype):
        # Overload sprite parent class
        super().__init__()

        # Enemy aircraft type, which is convenient for the later code to load resources of different types of enemy aircraft.
        self.enemytype = _enemytype
        # Load pictures of enemy aircraft of this type
        self.image = pg.image.load(ENEMY_FILE[_enemytype])
        # Enemy aircraft type health
        self.life = ENEMY_LIFE[_enemytype]
        # Score of enemy aircraft type
        self.score = ENEMY_SCORE[_enemytype]
        # Enemy aircraft type speed
        self.speed = ENEMY_SPEED[_enemytype]

        # Initial position of enemy aircraft
        self.rect = self.image.get_rect()
        self.rect.x = random.randint(1, SCREEN_RECT.width - self.rect.width)
        # They all appear from the top of the screen and fly out gradually
        self.rect.y = -self.rect.height

        # Firing probability
        self.firerate = random.randint(5,100)
        # Random motion mode, - 1 drifts to the left first, bounces after hitting the wall, 0 goes straight down, 1 drifts to the right first, bounces after hitting the wall
        self.moveto = random.randint(-1,1)

2. Self movement control (linear movement, left swing and right swing, S random change)

    # Enemy aircraft status update
    def update(self):
        # Random horizontal movement
        if random.randint(1,10) > 3:
            self.rect.x += self.speed * self.moveto
            if self.rect.x < 0:
                self.moveto = 1
                self.rect.x = 0
            elif self.rect.x > SCREEN_RECT.width:
                self.moveto = -1
                self.rect.x = SCREEN_RECT.width - self.rect.width
        # Move down
        self.rect.y += self.speed
        # If it exceeds the screen, it will be destroyed by itself
        if self.rect.y > SCREEN_RECT.height:
            self.kill()

3. The effect of being hit and the HP of different types of enemy aircraft (it's boring to kill with one shot)

    # Fighter damage function
    def breakdown(self, _losslife):
        # Hit sound (preloaded into memory)
        HIT_SOUND.play()
        # Destroyed score
        _score = 0
        # Every time you are hit, there will be different degrees of damage
        self.hitimage = pg.image.load(ENEMY_HIT_FILE[self.enemytype][ENEMY_LIFE[self.enemytype] - self.life])
        # Lose one grid of blood at a time
        self.life -= _losslife
        if self.life <= 0:
            # Destroyed, destroyed object, return score
            self.kill()
            _score = self.score
        else:
            # Only hit, not destroyed, change the effect
            self.image = self.hitimage
        return _score

4. Management of fired bullets (random firing probability, initial position control of bullets, and automatic destruction of bullets beyond the scope of the screen to prevent unnecessary occupation of computing resources.)

The firing code of the main class is very simple, mainly because "_BulletList" is the bullet Sprite Group of the main control unit. All bullet sprites generated by the enemy aircraft can be added to this Group for later collision detection. (add a question: you can think about the advantages and disadvantages of adding bullets to a Sprite Group in the enemy aircraft category?)

    # Fire attack
    def fire(self, _BulletList):
        if random.randint(1,30) < self.firerate:
            # ENEMY_BULLET_SOUND.play()
            _bullet = EnemyBullet(self.rect.x + self.rect.width // 2, self.rect.y + self.rect.height, self.speed)
            _bullet.add(_BulletList)

Specific bullet class implementation (this class also deserves improvement, that is, it can transfer the fighter type to generate different bullet effects. In addition, the processing of the initial position of the bullet is still a little rough.)

class EnemyBullet(pg.sprite.Sprite):
    # Bullet initialization
    def __init__(self, rx, ry, rs):
        # Overload parent class
        super().__init__()
        # Process default logic
        self.image = ENEMY_BULLET_PIC
        self.rect = self.image.get_rect()
        self.rect.x = rx
        self.rect.y = ry
        self.speed = rs + 1
    # Bullet status update
    def update(self):
        self.rect.y += self.speed
        # The bullet will destroy itself when it exceeds the screen to prevent resource occupation
        if self.rect.y > SCREEN_RECT.height:
            self.kill()

Initial filling part of the definition of global variables

# Enemy aircraft file
ENEMY_FILE = ['./images/enemy1.png', './images/enemy2.png', './images/enemy3.png']
ENEMY_HIT_FILE = [['./images/enemy1.png'],
                  ['./images/enemy2_hit.png','./images/enemy2_down1.png', './images/enemy2_down2.png', './images/enemy2_down3.png', './images/enemy2_down4.png'],
                  ['./images/enemy3_hit.png','./images/enemy3_n1.png','./images/enemy3_n2.png','./images/enemy3_n1.png','./images/enemy3_n2.png',
                   './images/enemy3_down1.png', './images/enemy3_down2.png', './images/enemy3_down3.png', './images/enemy3_down4.png','./images/enemy3_down5.png']]
# Enemy aircraft health
ENEMY_LIFE = [1,5,10]
# Enemy aircraft score
ENEMY_SCORE = [10,50,100]
# Enemy aircraft speed
ENEMY_SPEED = [3,2,1]

All resource links: https://pan.baidu.com/s/1-bKJFIEMghuU42mJFElSnQ Extraction code: 78ds

Environmental description:

IDE: Pycharm CE

Reference Library: pygame, random

Topics: Python Game Development pygame