π§ Section 10: Create the Player Class (Composition)
π Summary (What you will do)
In this section, you will create a Player class that owns pets. You will:
- Store a list of
Animalobjects inside the player - Add an
adopt()method that creates pets dynamically - Add simple XP leveling to unlock more adoption slots
This introduces composition: the player has animals, rather than is an animal.
β Checklist (You must complete these)
- Open
pet_manager.py - Find the
SPECIESdictionary - Right below it, add the
Playerclass shown below - Type the code by hand so you understand how composition works
β No new constants/settings are added in this section, so you do not need to edit the top-of-file constants.
π Core Concepts (New learning for this section)
1) Composition vs inheritance
Inheritance means is-a (a Dog is an Animal).
Composition means has-a (a Player has a list of animals).
This is a powerful idea:
- The player manages pets
- The pets keep their own stats and behavior
- The player can grow without changing the pet classes
2) Managing a list of objects
The player stores pets in a list:
self.animals: List[Animal] = []
We can add new pets to the list as they are adopted.
3) Simple leveling and unlock logic
The player has XP too.
Each time XP crosses a threshold, the player levels up and unlocks more pet slots.
The unlock system uses the UNLOCK_LEVELS list so the pacing is easy to tweak later.
π» Code to Write (Type this by hand in pet_manager.py)
Directions:
- Open
pet_manager.py - Find the
SPECIESdictionary - Directly below it, type the following code by hand:
π§ Code Review & Key Concepts (What important lines do)
The animals list
self.animals: List[Animal] = []
This list holds all the playerβs pets.
Each pet is a full Animal object with its own stats and behavior.
Adopting a pet
animal_cls = SPECIES[species]
pet = animal_cls(name)
This looks up the correct class and creates a new animal dynamically.
Player leveling
while self._xp >= self._xp_to_next():
The player can level up multiple times if a lot of XP is gained at once.
Unlocking new adoption slots
for req in UNLOCK_LEVELS:
if self.level >= req:
allowed += 1
Every time the playerβs level hits a threshold, the number of pets they can own increases.
π§ͺ Test File: s10_test.py
β Create this file
Create a new file in the same folder as pet_manager.py called:
s10_test.py
π» Code to write in s10_test.py
π§ What this test is doing (and how it works)
- We create a
Playerand adopt two pets - We check that the pets list grows
- We add a large amount of XP to force level-ups
- We print the player level and unlocked slots to confirm the logic
β Run the test:
python s10_test.py
If the pet count increases and the level changes, your Player class is working.

