The full text of this chapter, to read or revisit. To practise, do the exercises.
Exercise 1 — Team Builder
Create a `Team` class to manage Codémon:
1. `__init__(self, name)` — team name and empty `members` list
2. `add(self, codemon)` — add a Codémon to the team
3. `remove(self, name)` — remove a Codémon by name
4. `show(self)` — print the team name and all members
5. `__len__` — return the number of members
Test by adding 3 Codémon, removing one, and printing the team size.
Starter code
class Codemon:
def __init__(self, name, element, hp=100):
self.name = name
self.element = element
self.hp = hp
def __str__(self):
return f"{self.name} [{self.element}] - {self.hp}HP"
class Team:
# __init__ with name and empty members
# add(codemon)
# remove(name)
# show()
# __len__
# Create a team, add 3 Codémon, remove one, show team
Exercise 2 — Team Battle
Two Codémon battle! The rules:
1. Each Codémon deals `10` damage per attack
2. They take turns attacking until one faints (HP <= 0)
3. Print each attack and the winner!
Starter code
class Codemon:
def __init__(self, name, hp=50):
self.name = name
self.hp = hp
def attack(self, target):
target.hp -= 10
print(f"{self.name} hits {target.name}! ({target.hp}HP left)")
def is_alive(self):
return self.hp > 0
# Create 2 Codémon
# Battle loop: take turns until one faints
# Print the winner
Exercise 3 — Codémon Team Battle
Create a `Team` class that holds a list of Codémon!
1. A `Team` class with `name` and `members` (list of Codémon)
2. A `first_alive(self)` method that returns the first member with HP > 0
3. Battle two teams: each team's first alive Codémon attacks the other, until one team has none left
Starter code
class Codemon:
def __init__(self, name, hp=50):
self.name = name
self.hp = hp
def attack(self, target):
target.hp -= 10
print(f"{self.name} hits {target.name}! ({target.hp}HP)")
def is_alive(self):
return self.hp > 0
class Team:
def __init__(self, name, members):
pass
def first_alive(self):
pass
# Create 2 teams, battle!