Text-Based RPG Game Gaming Project in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; // Structure to define a character struct Character { string name; int health; int attack; int defense; // Function to perform an attack void attackEnemy(Character &enemy) { int damage = attack - enemy.defense; if (damage < 0) damage = 0; enemy.health -= damage; cout << name << " attacks " << enemy.name << " for " << damage << " damage!" << endl; } // Function to check if the character is alive bool isAlive() { return health > 0; } }; int main() { srand(static_cast<unsigned int>(time(0))); // Seed the random number generator // Create the player character Character player; player.name = "Hero"; player.health = 100; player.attack = 15; player.defense = 5; // Create the enemy character Character enemy; enemy.name = "Goblin"; enemy.health = 50; enemy.attack = 10; enemy.defense = 3; cout << "A wild " << enemy.name << " appears!" << endl; // Battle loop while (player.isAlive() && enemy.isAlive()) { player.attackEnemy(enemy); if (enemy.isAlive()) { enemy.attackEnemy(player); } cout << player.name << " health: " << player.health << endl; cout << enemy.name << " health: " << enemy.health << endl; } // Determine the outcome of the battle if (player.isAlive()) { cout << player.name << " has defeated the " << enemy.name << "!" << endl; } else { cout << player.name << " has been defeated by the " << enemy.name << "..." << endl; } return 0; } |
Explanation Character Structure: The Character structure defines a basic RPG character with attributes: name, health, attack, and defense. It includes methods for attacking an enemy (attackEnemy()) and checking if the character is still alive (isAlive()). Attack Logic: attackEnemy(): This function calculates the damage inflicted by subtracting the enemy’s defense from the character’s attack value. …