Skip to the content

Project: game characters

Python · Unit 13: Inheritance

You're going to program the characters of a game. They all have a name, power and 100 health, which never goes below 0. When they attack, they take away from the other whatever their damage() says.

The warrior hits for double their power. The wizard has little power, always 5, but adds their magic.

class Character:
    def __init__(self, name, power):
        self.name = name
        self.power = power
        self.health = 100

    def damage(self):
        return self.power

c = Character("Sofia", 12)
print(c.name, c.health, c.damage())

Prints

Sofia 100 12

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Complete attack so each character hits according to their class. Ana is a warrior, so it should print 70.

  2. 2. Write the code

    Write the two child classes of Character. Warrior: its damage() is double its power. Wizard: it's created with a name and magic, calls the parent with power 5 and stores self.magic; its damage() is the parent's plus its magic. simulate is already written: the warrior attacks the wizard, the wizard strikes back, and it returns both health values.

  3. 3. Write the code

    Write fight(a, b): they take turns attacking, a goes first, and as soon as one leaves the other at 0 health, it returns the winner's name. The classes are ready, and simulate creates Ana, the warrior, and Leo, the wizard.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →