Module 4 Lesson 11: Hands-on Projects
Building an RPG Combat System. Apply inheritance, encapsulation, and polymorphism to build a modular game engine from scratch.
Lesson 11: Module 4 Hands-on Projects
In this final project for Module 4, we will build a fantasy RPG Combat System. This project will require you to use every OOP concept we’ve learned: Classes, Inheritance, Private Attributes, and Polymorphism.
Project: The "Hero vs. Monster" System
We will build a modular system where different types of characters can battle each other.
1. The Base Class (models/entity.py)
class Entity:
def __init__(self, name, hp, power):
self.name = name
self.__hp = hp # Encapsulated HP
self.power = power
def get_hp(self):
return self.__hp
def take_damage(self, amount):
self.__hp -= amount
print(f"{self.name} took {amount} damage! HP remaining: {self.__hp}")
def is_alive(self):
return self.__hp > 0
2. The Hero and Monster Classes
class Hero(Entity):
def __init__(self, name, hp, power, job):
super().__init__(name, hp, power)
self.job = job
def attack(self, target):
print(f"{self.name} the {self.job} strikes with {self.power} force!")
target.take_damage(self.power)
class Monster(Entity):
def attack(self, target):
print(f"{self.name} lunges at {target.name}!")
target.take_damage(self.power)
3. Combat Logic (game.py)
hero = Hero("Aragorn", 100, 20, "Ranger")
enemy = Monster("Orc", 50, 10)
print("--- BATTLE START ---")
while hero.is_alive() and enemy.is_alive():
hero.attack(enemy)
if enemy.is_alive():
enemy.attack(hero)
if hero.is_alive():
print(f"{hero.name} is victorious!")
else:
print("Game Over. The monster won.")
Module 4 Recap: Exercises and Quiz
Exercise 1: Property Additions
Add a level attribute to the Entity class and create a method level_up() that increases hp and power.
Exercise 2: New Subclass
Create a Mage class that inherits from Hero and overrides the attack() method to use magic damage instead of physical power.
Module 4 Quiz
1. Which concept emphasizes hiding internal data? A) Inheritance B) Polymorphism C) Encapsulation D) Composition
2. Which keyword is used to access a parent class's method?
A) parent
B) master
C) super
D) this
3. In the "is-a" vs. "has-a" rule, which corresponds to Composition? A) Is-a B) Has-a
4. True or False: A class method receives self as the first argument.
5. What is "Method Overriding"? A) Calling a method too many times. B) Replacing a parent class's method with a new version in a child class. C) Deleting a method from a class.
Quiz Answers
- C | 2. C | 3. B | 4. False (It receives
cls) | 5. B
Conclusion
You’ve mastered Object-Oriented Programming! This is a massive milestone. Most modern applications are built using these exact principles.
In Module 5: File Handling and Error Management, we’ll learn how to save our game data permanently to your computer and how to prevent our programs from crashing!