The full text of this chapter, to read or revisit. To practise, do the exercises.
Exercise 1 — Basic Codémon
Create a `Codemon` class with:
1. `__init__` taking `name`, `element`, `level` (default 1), `hp` (default 100)
2. A `__str__` method that returns `"Aquachu [Water] Lv.1 - 100HP"`
3. Create 2 Codémon and print them
Starter code
class Codemon:
# Create __init__ with name, element, level (default 1), hp (default 100)
# Create __str__ that returns "Name [Element] Lv.X - YHP"
# Create 2 Codémon and print them
Exercise 2 — Battle Methods
Build on the `Codemon` class and add:
1. `attack(self, target)` — deals `level * 3` damage to target's HP. Print `"X attacks Y for Z damage!"`
2. `heal(self, amount)` — restores HP but caps at 100 (max HP)
3. `is_alive(self)` — returns `True` if HP > 0
4. Create 2 Codémon and make them fight until one faints!
Starter code
class Codemon:
def __init__(self, name, element, level=1, hp=100):
self.name = name
self.element = element
self.level = level
self.hp = hp
def __str__(self):
return f"{self.name} [{self.element}] Lv.{self.level} - {self.hp}HP"
# Add attack(self, target)
# Add heal(self, amount) - cap at 100
# Add is_alive(self)
# Create 2 Codémon and battle until one faints
Exercise 3 — Codémon with Moves
Time for composition! Create:
1. A `Move` class with `name` and `power`
2. A `Codemon` class with `name`, `hp`, and a `moves` list
3. A `best_move(self)` method that returns the strongest move
4. A `use_move(self, move_name, target)` method that deals damage
5. Create 2 Codémon and make one attack the other!
Starter code
class Move:
# name, power
pass
class Codemon:
# name, hp, moves
pass
def best_move(self):
pass
def use_move(self, move_name, target):
pass
# Create 2 Codémon with moves, attack!