Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Composition Implementation | Komposition
Objektorientierte Programmierung in Python

Composition Implementation

Swipe um das Menü anzuzeigen

The great way to show composition is to build an RPG warrior system step by step. Starting from simple equipment classes and ending with a fully interactive warrior, each component contributes to a dynamic and flexible design.

Note
Note

Even if certain classes like Armor or Shield do not participate in calculations immediately, it is useful to create them early. They complete the warrior’s gear, improve clarity, and prepare the system for future extensions.

The system begins with the Weapon class. It defines three attributes—name, attack, and weapon type—and includes a string method that produces readable output such as “Broadsword, Attack 20”. The next step introduces Armor, Helmet, and Shield classes. Each has a name, a defense value, and a material type, also supported by string methods.

The Enemy class adds interaction. With a single attribute (HP) and a method take_damage(), it reacts to attacks by reducing health, printing the amount lost, and announcing defeat when health reaches zero.

The centerpiece is the Warrior class. Instead of raw stats, it holds full instances of other classes: armor, helmet, and shield are assigned at creation, while the weapon slot starts empty. The warrior can:

  • equip a weapon dynamically using equip_weapon(),
  • attack an enemy with the weapon’s attack value,
  • display status by pulling information from the composed gear.

This RPG warrior system illustrates how multiple objects interact to create dynamic behavior. Weapons define damage, gear completes the warrior’s identity, and enemies provide feedback through combat. The result is a modular structure where different configurations lead to different outcomes, making the system both reusable and adaptable.

question mark

Which statement best illustrates the role of composition in the RPG warrior system?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 3

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 3. Kapitel 3
some-alt