Python RPG Game (Part 1)
How to create your own text-based RPG in Python using Object Oriented Programming.
I spent 15 days creating this RPG Game in Python, if you want to skip the tutorial and go straight to the code and read it, here’s the project in GitHub!
By the end of this series of articles, you’ll be able to create something like the GIF you see down below, where you’ll have a text-based RPG which I’ll be covering in a set of articles.
If you have any improvements on the code or any suggestions, please let me know. Have fun and enjoy the article!
In the following article I’ll be covering the:
- Hero Class (with its Getters and Setters)
- Enemy Class (with its Getters and Setters)
Step 1: Hero Class
There are 7 different attributes for the Hero class, which would be the hero:
- Health = Hhealth
- Attack = Hattack
- Luck = Hluck
- Ranged = Hranged
- Defense = Hdefence
- Magic = Hmagic
- Name = Hname
Setters and Getters
We’re going to use these attributes for the setters and getters which are ways to call the attributes of the Hero and edit its attributes. For example if the Hero gets attacked, we can call the attribute “Hhealth” and reduce its health or if the Hero level up, then we can increase the attribute “Hhealth”.
We use getters & setters to add validation logic around getting and setting a value. The way we create a Getter in Python, is like this:
Is like any other method for a class, and we’re calling the function “getHealth”, because we’re going to use it for later in the game whenever we want to call the function to edit the health of the Hero.
The way we create a Setter in Python, is like this:
def setHealth(self, newHealth):
self.health = newHealth
Here’s a pretty good example from geeksforgeeks which explains how setters and getters work in Python:
class Geek:def __init__(self, age = 0):
self._age = age# getter method
return self._age# setter method
def set_age(self, x):
self._age = xraj = Geek()# setting the age using setter
raj.set_age(21)# retrieving age using getter
Hero Class Code:
Step 2: Enemy Class
Similar to the Hero Class, in the Enemy Class we’re going to use setters and getters, but we’re going to create a subclass: “The Boss”
The way we’re going to do this is by simply inheriting the enemy class as the parent class and we’re going to use the boss class as the child class. You can do it by doing the following:
def __init__(self, Ehealth, Eattack, Especial, Echance, Ename, EsuperMove):
# in order to actually inherit the Enemy class we need to use the super method
super().__init__(Ehealth, Eattack, Especial, Echance, Ename)
self.superMove = EsuperMove
Credits: Youtube, Advanced Python Text Adventure.