Section 3. Chapter 4
single
Challenge: Building a Composed Warrior
Swipe to show menu
Task
Swipe to start coding
Practice using composition by building a simple warrior game:
-
Create a
Weaponclass with anameandattackvalue. -
Create a
Warriorclass with anamethat can equip a weapon (store it as an attribute). -
The warrior should start without a weapon (
None). -
Add a method
equip_weapon()to assign a weapon to the warrior. -
Add a method
show_weapon()that returns a string describing the current weapon:- If unarmed →
<Name> is unarmed"; - If armed →
<Name> is holding a <weapon>".
- If unarmed →
-
Equip the warrior with the weapon.
-
Use composition. The warrior should have a weapon, not inherit from it.
Solution
Everything was clear?
Thanks for your feedback!
Section 3. Chapter 4
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat