Project: game characters
Python · Unit 13: Inheritance
- Full plan
- Python
- Project
- 3 exercises
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. Complete the code
Complete
attackso each character hits according to their class. Ana is a warrior, so it should print 70.2. Write the code
Write the two child classes of
Character.Warrior: itsdamage()is double its power.Wizard: it's created with a name and magic, calls the parent with power 5 and storesself.magic; itsdamage()is the parent's plus its magic.simulateis already written: the warrior attacks the wizard, the wizard strikes back, and it returns both health values.3. Write the code
Write
fight(a, b): they take turns attacking,agoes first, and as soon as one leaves the other at 0 health, it returns the winner's name. The classes are ready, andsimulatecreates Ana, the warrior, and Leo, the wizard.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.