Editor

Classes and inheritance: many kinds of enemy

Pygame fundamentals · Lesson 7 of 8

A class describes one kind of thing in your game, and inheritance makes a new kind from an old one by writing only what is different.

A class is a blueprint

A class describes one kind of thing: the data each one keeps and what it can do. class Enemy: below says every enemy has a rect, a speed and a color, and can move() and draw() itself. Functions written inside a class are its methods.

Enemy(60, 0) makes one enemy, an object, from the class. Python runs __init__ to set it up, and self is the enemy being set up or used. Each enemy keeps its own values: the third one is made faster and yellow, and the other two stay as they were.

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 320))
clock = pygame.time.Clock()


class Enemy:
    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, 26, 26)
        self.speed = 2
        self.color = (235, 95, 85)

    def move(self):
        self.rect.y += self.speed
        if self.rect.top > 320:  # off the bottom: back to the top
            self.rect.bottom = 0
            self.rect.x = random.randint(0, 454)

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, self.rect, border_radius=6)


enemies = [Enemy(60, 0), Enemy(220, -120), Enemy(380, -240)]
enemies[2].speed = 4  # each enemy keeps its own values
enemies[2].color = (255, 212, 59)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    for enemy in enemies:
        enemy.move()

    screen.fill((16, 18, 22))
    for enemy in enemies:
        enemy.draw(screen)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

A new kind from an old one

class Bouncer(Enemy): makes a new kind of enemy from the old one. Bouncer is a child class of Enemy, and Enemy is its parent. A Bouncer gets everything an Enemy has, __init__ and draw() included, without writing them again.

A child class writes only what is different. Bouncer and Chaser each write their own move(), which replaces Enemy's for them: this is called overriding. Values that every enemy of one kind shares, like color and label, sit in the class itself, so each child class can set its own.

The main loop calls enemy.move(player) on every enemy without asking what kind it is, and each one moves its own way. That is why every move() takes player, even Enemy's, which does not use it.

import math
import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 320))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 24)
player = pygame.Rect(222, 290, 36, 18)


class Enemy:
    color = (235, 95, 85)  # shared by every Enemy
    label = "Enemy"

    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, 26, 26)
        self.speed = 2

    def move(self, player):
        self.rect.y += self.speed

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, self.rect, border_radius=6)


class Bouncer(Enemy):  # a Bouncer is an Enemy...
    color = (90, 162, 224)
    label = "Bouncer"

    def move(self, player):  # ...that moves its own way
        self.rect.y += self.speed
        self.rect.x += round(math.sin(self.rect.y / 18) * 3)


class Chaser(Enemy):
    color = (255, 212, 59)
    label = "Chaser"

    def move(self, player):
        self.rect.y += self.speed
        if self.rect.centerx < player.centerx:
            self.rect.x += 1
        elif self.rect.centerx > player.centerx:
            self.rect.x -= 1


enemies = []
spawn_timer = 0

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player.x -= 5
    if keys[pygame.K_RIGHT]:
        player.x += 5
    player.clamp_ip(screen.get_rect())

    spawn_timer += 1
    if spawn_timer >= 40:
        spawn_timer = 0
        kind = random.choice([Enemy, Bouncer, Chaser])
        enemies.append(kind(random.randint(20, 430), -30))

    for enemy in enemies:
        enemy.move(player)  # the same call: each kind moves its own way
    enemies = [e for e in enemies if e.rect.top < 320]

    screen.fill((16, 18, 22))
    for enemy in enemies:
        enemy.draw(screen)  # draw() comes from Enemy for all three
        screen.blit(font.render(enemy.label, True, enemy.color), (enemy.rect.x, enemy.rect.y - 16))
    pygame.draw.rect(screen, (230, 232, 235), player, border_radius=5)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

super(): keep what the parent does, then add

Sometimes a child class needs everything the parent does, and then a little more. The Tank in the game below starts its __init__ with super().__init__(x, y). super() reaches the parent class, so Enemy sets up the rect and the speed as it does for every enemy. Then the Tank adds its own: a bigger rect, a slower speed and self.hp = 3.

Its draw() works the same way: super().draw(surface) draws the body as every enemy does, then the Tank draws its health bar on top. Without the super() call in __init__, a Tank would have no rect, and the game would stop with an AttributeError.

One loop for every kind

Move with the arrow keys and shoot with Space. Every kind of enemy has the same three methods, move(), hit() and draw(), so the main loop treats them all alike. hit() answers whether one bullet destroyed the enemy: an Enemy says yes at once, a Tank only at its third hit.

A class is a value too. random.choice([Enemy, Enemy, Bouncer, Chaser, Tank]) picks a class, and kind(x, -30) makes an enemy of that kind. Enemy is in the list twice, so plain enemies come twice as often.

To add a new kind of enemy, write one new class. Nothing in the main loop changes.

import math
import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 320))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 28)


class Enemy:
    color = (235, 95, 85)
    points = 10

    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, 26, 26)
        self.speed = 2

    def move(self, player):
        self.rect.y += self.speed

    def hit(self):
        return True  # one bullet is enough

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, self.rect, border_radius=6)


class Bouncer(Enemy):
    color = (90, 162, 224)
    points = 20

    def move(self, player):
        self.rect.y += self.speed
        self.rect.x += round(math.sin(self.rect.y / 18) * 3)


class Chaser(Enemy):
    color = (255, 212, 59)
    points = 30

    def move(self, player):
        self.rect.y += self.speed
        if self.rect.centerx < player.centerx:
            self.rect.x += 1
        elif self.rect.centerx > player.centerx:
            self.rect.x -= 1


class Tank(Enemy):
    color = (160, 110, 230)
    points = 50

    def __init__(self, x, y):
        super().__init__(x, y)  # Enemy sets up the rect and the speed
        self.rect.inflate_ip(14, 14)  # then a Tank is bigger,
        self.speed = 1  # slower,
        self.hp = 3  # and takes three hits

    def hit(self):
        self.hp -= 1
        return self.hp == 0

    def draw(self, surface):
        super().draw(surface)  # the body, as every enemy
        bar = pygame.Rect(self.rect.x, self.rect.y - 7, self.rect.width * self.hp // 3, 4)
        pygame.draw.rect(surface, (127, 210, 155), bar)


def new_game():
    return pygame.Rect(222, 290, 36, 20), [], [], 0, 3


player, enemies, bullets, score, lives = new_game()
spawn_timer = 0

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            if lives > 0:
                bullets.append(pygame.Rect(player.centerx - 2, player.top - 10, 4, 10))
            else:
                player, enemies, bullets, score, lives = new_game()

    if lives > 0:
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            player.x -= 5
        if keys[pygame.K_RIGHT]:
            player.x += 5
        player.clamp_ip(screen.get_rect())

        spawn_timer += 1
        if spawn_timer >= 45:
            spawn_timer = 0
            kind = random.choice([Enemy, Enemy, Bouncer, Chaser, Tank])  # a class is a value
            enemies.append(kind(random.randint(20, 430), -30))

        for bullet in bullets:
            bullet.y -= 8
        survivors = []
        for enemy in enemies:
            enemy.move(player)  # each kind moves its own way
            i = enemy.rect.collidelist(bullets)
            if i >= 0:
                bullets.pop(i)
                if enemy.hit():  # a Tank needs three
                    score += enemy.points
                    continue
            if enemy.rect.colliderect(player) or enemy.rect.top > 320:
                lives -= 1
                continue
            survivors.append(enemy)
        enemies = survivors
        bullets = [b for b in bullets if b.bottom > 0]

    screen.fill((16, 18, 22))
    for enemy in enemies:
        enemy.draw(screen)  # and draws its own way
    for bullet in bullets:
        pygame.draw.rect(screen, (230, 232, 235), bullet)
    pygame.draw.polygon(screen, (230, 232, 235), [(player.centerx, player.top), (player.left, player.bottom), (player.right, player.bottom)])
    screen.blit(font.render(f"Score {score}   Lives {max(lives, 0)}", True, (230, 232, 235)), (12, 10))
    if lives <= 0:
        text = font.render("Game over. Press Space to play again", True, (255, 212, 59))
        screen.blit(text, text.get_rect(center=(240, 160)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Next: pygame's own parent class

pygame has parent classes of its own. In the next lesson, class Player(pygame.sprite.Sprite): makes Player a child of pygame's Sprite class, and super().__init__() lets Sprite set itself up before Player adds its image and rect. It is the same idea as Tank and Enemy here.

Your turn

Change the programs above in the game panel, then press Run.

  • Add a Zigzag enemy that slides sideways and turns back at the edges of the window. It needs a direction of its own, so give it an __init__ that calls super().__init__(x, y) and then sets self.dx = 3.
  • Make a Boss class that inherits from Tank: twice as big, ten hits, 200 points. Which methods does it need to write, and which does it get for free?
  • Make Chasers faster when they are close to the player, by changing only the Chaser class.

Space Shooter keeps invaders, bullets and bombs apart: which of them could share a parent class? Open Space Shooter.

More on this: Inheritance in Python · A program that shows inheritance