🧍 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 Animal objects 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 SPECIES dictionary
  • Right below it, add the Player class 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:

  1. Open pet_manager.py
  2. Find the SPECIES dictionary
  3. Directly below it, type the following code by hand:

Code image: s10-code


🧠 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

Code image: s10-test

🧠 What this test is doing (and how it works)

  • We create a Player and 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.