Click here to Skip to main content
15,886,693 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Here is the code for the project, I need to work at implementing inheritance for it. I would like to have some virtual functions and make it a class driven program which uses derived classes and has a base class. The derived clase should inherit the features from the base class and utilize the extra features.


C++
<pre>#include <iostream>
#include <cmath>
#include <climits>
#include <string>
#include "Mastermega.h"
#include "EquipmentStore.h"
using namespace std;

int main()
{
    cout<<"Welcome to Master Mage Tournament\n";
    Mastermega m;
    EquipmentStore eq;
    m.gamesimulation();
    eq.equip_store();
    return 0;
}

////mastermega.h

#ifndef MASTERMEGA_H
#define MASTERMEGA_H
#include <string>
using namespace std;

class Mastermega
{
    public:
        string PlayerName;
        int PlayerHealth = 10;
        int PlayerHealthArmor = 0;
        int PlayerArmor = 0;
        int PlayerExperience = 0;
        int PlayerLevel = 1;
        int PlayerMoney = 2100;
        int PlayerWeapon = 1;
        int PlayerDamage = 1;
    void gamesimulation();
    void intro();
    void mainmenu();
    void arena();
    void fight();
    void store();
    void stats();
    void about();
    void experiencecheck();
    void weaponcheck();
    void savegame();
    void loadgame();
    void newPlayer();
};

#endif

/////mastermega.cpp

#include <iostream>
#include <cmath>
#include <climits>
#include <string>
#include <time.h>       /* time */
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <conio.h>
#include <fstream>
#include <sstream>
using namespace std;
#include "Mastermega.h"
#include "arena.h"
Arena a;

void Mastermega::gamesimulation()
{
    intro();
    mainmenu();
}
void Mastermega::intro()
{
cout << "\033[2J\033[1;1H";//clear screen in onlinggdb
system("cls");//clear screen in codeblocks compiler
    cout<<"\n\t\t#     #                                                                "<< endl;
 cout<<" \t\t##   ##   ##    ####  ##### ###### #####                               "<< endl;
 cout<<" \t\t# # # #  #  #  #        #   #      #    #                              "<< endl;
 cout<<" \t\t#  #  # #    #  ####    #   #####  #    #                              "<< endl;
 cout<<" \t\t#     # ######      #   #   #      #####                               "<< endl;
 cout<<" \t\t#     # #    # #    #   #   #      #   #                               "<< endl;
 cout<<" \t\t#     # #    #  ####    #   ###### #    #                              "<< endl;
 cout<<"                                                                        "<< endl;
 cout<<" #######                                                                "<< endl;
 cout<<"    #     ####  #    # #####  #    #   ##   #    # ###### #    # #####  "<< endl;
 cout<<"    #    #    # #    # #    # ##   #  #  #  ##  ## #      ##   #   #    "<< endl;
 cout<<"    #    #    # #    # #    # # #  # #    # # ## # #####  # #  #   #    "<< endl;
 cout<<"    #    #    # #    # #####  #  # # ###### #    # #      #  # #   #    "<< endl;
 cout<<"    #    #    # #    # #   #  #   ## #    # #    # #      #   ##   #    "<< endl;
 cout<<"    #     ####   ####  #    # #    # #    # #    # ###### #    #   #    "<< endl;
 cout<<"                                                                        "<< endl;
 cout<<"\t\t    #                                                                   "<< endl;
 cout<<"\t\t   # #   #####  ###### #    #   ##                                      "<< endl;
 cout<<"\t\t  #   #  #    # #      ##   #  #  #                                     "<< endl;
 cout<<"\t\t #     # #    # #####  # #  # #    #                                    "<< endl;
 cout<<"\t\t ####### #####  #      #  # # ######                                    "<< endl;
 cout<<"\t\t #     # #   #  #      #   ## #    #                                    "<< endl;
 cout<<"\t\t #     # #    # ###### #    # #    #                                    \n"<< endl;


  cout << R"(
Master Mage Arena                 |>>>
----------------                  |
                    |>>>      _  _|_  _         |>>>
                    |        |;| |;| |;|        |
                _  _|_  _    \\.    .  /    _  _|_  _
               |;|_|;|_|;|    \\:. ,  /    |;|_|;|_|;|
               \\..      /    ||;   . |    \\.    .  /
                \\.  ,  /     ||:  .  |     \\:  .  /
                 ||:   |_   _ ||_ . _ | _   _||:   |
                 ||:  .|||_|;|_|;|_|;|_|;|_|;||:.  |
                 ||:   ||.    .     .      . ||:  .|
                 ||: . || .     . .   .  ,   ||:   |       \,/
                 ||:   ||:  ,  _______   .   ||: , |            /`\
                 ||:   || .   /+++++++\    . ||:   |
                 ||:   ||.    |+++++++| .    ||: . |
              __ ||: . ||: ,  |+++++++|.  . _||_   |
     ____--`~    '--~~__|.    |+++++__|----~    ~`---,              ___
-~--~                   ~---__|,--~'                  ~~----_____-~'   `~----~~

    )" << endl;
 cout << "\n Press enter to fight in the Arena..." << endl;
 std::cin.get();
}

void Mastermega::mainmenu()
{
    experiencecheck();
//  a.getinfo();
cout << "\n Press enter to go to the Main Menu..." << endl;
 std::cin.get();
    short int choice;
 system("clear");
    cout << "\n\n\t\tWelcome to the arena " << PlayerName << "!\n\n";

    //MENU
        cout << "\n0) New Player \n1) Arena \n2) Store \n3) Statistics \n4) About\n5) Save Game\n6) Load Game\n7) Exit\n\n";
    cout << "Menu Choice: ";
    cin >> choice;



    //CHECKS MENU CHOICE
    
    if (choice == 1)
    {

        arena();
    }
    else if (choice == 2)
    {

        store();
    }
    else if (choice == 3)
    {

        stats();
    }
    else if (choice == 4)
    {

        about();
    }
    else if (choice == 5)
    {

        savegame();
    }
    else if (choice == 6)
    {

        loadgame();
    }
    else if (choice == 7)
    {
exit(0);
        
    }
    else if (choice == 0)
    {

        newPlayer();
    }



}

void Mastermega::newPlayer(){
    cout <<"\n-New Player-\n" << endl;
    cout <<"What is your player's name?"<<endl;
    cin >> PlayerName;
    system("clear");
    cout <<"\nHere are your stats:\n";
    //get name
    // make name
    //PlayerName = 
    //show stats
    stats();
    std::cin.get();
    
}

void Mastermega::store()
{
    int menuchoice;

    cout << "---Welcome to the Store--- \n\n\n";

    cout << "Your Gold: "<< PlayerMoney <<"\n\n";

    cout << "Weapons Available: \n\n";
    cout << "1)  Fire Staff +1: $40\n"; // Extra Damage: 1
    cout << "2)  Poison Staff +2: $50\n";  // Extra Damage: 2
    cout << "3)  Lightning Staff +3: $80\n";  // Extra Damage: 3
    cout << "4)  Ice Staff +4: $150\n\n";  // Extra Damage: 4

    cout << "Armor: \n\n";
    cout << "5)  +5 Armor: $50\n"; // Reduce damage to self by 5
    cout << "6)  +10 Armor: $100\n\n"; // Reduce damage to self by 10

    cout << "7) Play Menu: 7\n\n\n"; // Goes back to prior menu

    cout << "Select an option: ";
    cin >>menuchoice;

    //balance check
    if(menuchoice == 1)
    {
        if(PlayerMoney < 40)
        {

            cout << "Not enough money, returning to main menu";
            system("PAUSE");

            mainmenu();
        }
        else
        {

            cout << "Thanks for you business!\n\n";
            system("PAUSE");

            PlayerMoney -= 40;
            PlayerWeapon = 1;
            mainmenu();

        }
    }
    else if(menuchoice == 2)
    {
        if(PlayerMoney < 50)
        {

            cout << "Sorry, not enough cash";
            system("PAUSE");

            mainmenu();
        }
        else
        {

            cout << "Transaction made!\n\n";
            system("PAUSE");

            PlayerMoney -= 50;
            PlayerWeapon = 2;
            mainmenu();
        }
    }
    else if(menuchoice == 3)
    {
        if(PlayerMoney < 80)
        {

            cout << "Sorry, not enough cash";
            system("PAUSE");

            mainmenu();
        }
        else
        {

            cout << "Transaction made!\n\n";
            system("PAUSE");

            PlayerMoney -= 80;
            PlayerWeapon = 3;
            mainmenu();
        }
    }
    else if(menuchoice == 4)
    {
        if(PlayerMoney < 150)
        {

            cout << "Transaction made";
            system("PAUSE");

            mainmenu();
        }
        else
        {

            cout << "Transaction made!\n\n";
            system("PAUSE");

            PlayerMoney -= 150;
            PlayerWeapon = 4;
            mainmenu();
        }
    }
    else if(menuchoice == 5)
    {
        if(PlayerMoney < 50)
        {

            cout << "Sorry, not enough cash";
            system("PAUSE");

            mainmenu();
        }
        else
        {

            cout << "Transaction made!\n\n";
            system("PAUSE");

            PlayerMoney -= 50;
            PlayerArmor += 5;
            mainmenu();
        }

    }
    else if(menuchoice == 5)
    {
        if(PlayerMoney < 100)
        {

            cout << "Sorry, not enough cash";
            system("PAUSE");

            mainmenu();
        }
        else
        {

            cout << "Transaction made!\n\n";
            system("PAUSE");

            PlayerMoney -= 100;
            PlayerArmor += 10;
            mainmenu();
        }
    }
    if (menuchoice == 7)
    {

        cout << "You are through shopping.\n\n";
        system("PAUSE");

        mainmenu();
    }
}

void Mastermega::stats()
{
    experiencecheck();
    weaponcheck();

    cout << "Stats: \n\n\n";

    cout << "Name: " << PlayerName<<"\n";
    cout << "Health: " << PlayerHealth<<"\n";
    cout << "Armor: " << PlayerArmor<<"\n";
    cout << "EXP: " << PlayerExperience<<"\n";
    cout << "Level: " << PlayerLevel << "\n";
    cout << "Money: " << PlayerMoney<<"\n";
    cout << "Damage: " << PlayerDamage << "\n";

    //Shows Weapon
    if (PlayerWeapon == 1)
    {
        cout << "Weapon: fire staff\n\n";
    }
    else if (PlayerWeapon == 2)
    {
        cout << "Weapon: poison staff\n\n";
    }
    else if (PlayerWeapon == 3)
    {
        cout << "Weapon: lightning staff\n\n";
    }
    else if (PlayerWeapon == 4)
    {
        cout << "Weapon: ice staff\n\n";
    }
    else if (PlayerWeapon == 5)
    {
        cout << "Weapon: megastaff\n\n";
    }
cout << "Press Enter..."<<endl;
    //back to menu
std::cin.get();
//  system("PAUSE");

    mainmenu();
}

void Mastermega::about()
{
        cout << "Game by Gabriel Sharp.. In order to play you must choose an option:\n\n";
cout << "Arena: You will fight a random monster\n\n";
cout << "Store: You can upgrade your weapons and armor which cause more damage and protect you\n\n";
cout << "Experience is gained by killing monsters and you will cause more damage:\n\n";


printf("Press enter to continue...\n"); 
std::cin.get();
//  system("PAUSE");

    mainmenu();
}

void Mastermega::savegame()
{
    cout << "\n-1) Save New Game -\n2) Overwrite Save Game -" << endl;
    
        cout << "Menu Choice: ";
        short int choice;
    cin >> choice;

    // menu options
    
    if (choice == 1)
    {
ofstream myfile ("savefile.txt"); 

  if (myfile.is_open()) 

  { 

myfile<< "\t\t\t" << PlayerName << " " << PlayerHealth << " " << PlayerArmor <<" " << PlayerExperience <<" " << PlayerLevel <<" " << PlayerDamage <<" " << PlayerWeapon <<  "\n"; 

    myfile.close(); 
    cout << "\n\t--Game Saved--\t" << endl;
    //cout << "\n Press enter to go to the Main Menu..." << endl;
 std::cin.get();

  } 

  else cout << "Unable to open file"; 
  //cout << "\n Press enter to go to the Main Menu..." << endl;
 std::cin.get();
 
 mainmenu();
        
    }
    else if (choice == 2)
    {
cout << "Truncate" << endl;

/////////
 std::ofstream ofs("savefile.txt", std::ofstream::trunc);

   ofs << PlayerName << " " << PlayerHealth << " " << PlayerArmor <<" " << PlayerExperience <<" " << PlayerLevel <<" " << PlayerDamage <<" " << PlayerWeapon <<  "\n"; 


   ofs.close();
////////
cout << "\n\t\tGame Saved" << endl;
std::cin.get();
mainmenu();
        
    }
    
    
    
    
 
}

void Mastermega::loadgame() 
{
    cout <<"\n- Load Game? -" << endl;
    
    ifstream inputFile("savefile.txt");
    string line;

    while (getline(inputFile, line))
    {
        istringstream ss(line);

        string name;
         ss >> PlayerName >> PlayerHealth >> PlayerArmor >> PlayerExperience >> PlayerLevel >> PlayerDamage >> PlayerWeapon ; 

        cout << PlayerName << ", " << PlayerHealth << ", " << PlayerArmor <<", " << PlayerExperience <<", " << PlayerLevel <<", " << PlayerDamage <<", " << PlayerWeapon << endl; 

    } 
    cout <<"\n\t\t--Game Loaded--\n"<<endl;
    cout << "\n Press enter to go to the Main Menu..." << endl;
 std::cin.get();
 
    mainmenu();
}




//experiencecheck
void Mastermega::experiencecheck()
{/*

    }*/
}

void Mastermega::weaponcheck()
{
    if (PlayerWeapon == 1)
    {
        PlayerDamage = 5;
    }
    else if (PlayerWeapon == 2)
    {
        PlayerDamage = 10;
    }
    else if (PlayerWeapon == 3)
    {
        PlayerDamage = 15;
    }
    else if (PlayerWeapon == 4)
    {
        PlayerDamage = 20;
    }
    else if (PlayerWeapon == 5)
    {
        PlayerDamage = 25;
    }
}

///FIGHT
void Mastermega::arena()
{
    short int menuchoice;



    //Starting Battle
    cout << "\n\nHere you will fight \n\n";
    cout << "Fight: 1";
    cout << "\nMain Menu: 2\n\nChoice: ";
    cin >> menuchoice;
    if(menuchoice == 1)
    {
        fight();
    }
    else if(menuchoice == 2)
    {

        mainmenu();
    }
}

void Mastermega::fight()
{
//
//
    short int monster = 1;
    int monsterhealth = 0;
    int monsterdamage = 0;

    weaponcheck();

    PlayerHealthArmor = PlayerHealth + (PlayerArmor/2); //Armor Rating


srand (time(NULL));
monster = rand() % 5 + 1;     // v2 in the range 1 to 100
//  monster = 1;

    if (monster == 1)//
    {
        cout << "A goblin attacks...\n\n";
         cout << R"(
              ,      ,
            /(.-""-.)\
        |\  \/      \/  /|
        | \ / =.  .= \ / |
        \( \   o\/o   / )/
         \_, '-/  \-' ,_/
           /   \__/   \
           \ \__/\__/ /
         ___\ \|--|/ /___
       /`    \      /    `\
      /       '----'       \
    )" << endl; //
        system("PAUSE");


        monsterhealth = 5;
        monsterdamage = 5;

        cout << "Goblin defeated!\n\n";
        system("PAUSE");


        PlayerExperience += 20;
        PlayerMoney += 50;
cout << "Experience" << PlayerExperience << "--> " << endl;
cout << "Money" <<  PlayerMoney << "--> " << endl;
        arena();
    }
    else if(monster == 2)//
    {
        cout << "Fight a giant scorpion...\n\n";
         cout << R"(
                ___ __
     _{___{__}\
    {_}      `\)
   {_}        `            _.-''''--.._
   {_}                    //'.--.  \___`.
    { }__,_.--~~~-~~~-~~-::.---. `-.\  `.)
     `-.{_{_{_{_{_{_{_{_//  -- 8;=- `
        `-:,_.:,_:,_:,.`\\._ ..'=- ,
            // // // //`-.`\`   .-'/
           << << << <<    \ `--'  /----)
            ^  ^  ^  ^     `-.....--'''

    )" << endl; //
        system("PAUSE");


        monsterhealth = 10;
        monsterdamage = 10;

        cout << "Scorpion dies!\n\n";
        system("PAUSE");


        PlayerExperience += 25;
        PlayerMoney += 100;
cout << "Experience" << PlayerExperience << "--> " << endl;
cout << "Money" <<  PlayerMoney << "--> " << endl;
        arena();
    }
    else if(monster == 3)//
    {
        cout << "Fight a giant spider...\n\n";
         cout << R"(

        /\  .-"""-.  /\
       //\\/  ,,,  \//\\
       |/\| ,;;;;;, |/\|
       //\\\;-"""-;///\\
      //  \/   .   \/  \\
     (| ,-_| \ | / |_-, |)
       //`__\.-.-./__`\\
      // /.-(() ())-.\ \\
     (\ |)   '---'   (| /)
      ` (|           |) `
        \)           (/

    )" << endl; //
        system("PAUSE");


        monsterhealth = 10;
        monsterdamage = 10;

        cout << "Spider Dies!\n\n";
        system("PAUSE");


        PlayerExperience += 25;
        PlayerMoney += 100;
cout << "Experience" << PlayerExperience << "--> " <<  endl;
cout << "Money" <<  PlayerMoney << "--> " << endl;
        arena();
    }
    else if(monster == 4)//
    {
        cout << "Ork attacks...\n\n";
         cout << R"(
                   (    )
                  ((((()))
                  |o\ /o)|
                  ( (  _')
                   (._.  /\__
                  ,\___,/ '  ')
    '.,_,,       (  .- .   .    )
     \   \\     ( '        )(    )
      \   \\    \.  _.__ ____( .  |
       \  /\\   .(   .'  /\  '.  )
        \(  \\.-' ( /    \/    \)
         '  ()) _'.-|/\/\/\/\/\|
             '\\ .( |\/\/\/\/\/|
               '((  \    /\    /
               ((((  '.__\/__.')
                ((,) /   ((()   )
                 "..-,  (()("   /
            pils  _//.   ((() ."
          _____ //,/" ___ ((( ', ___
                           ((  )
                            / /
                          _/,/'
                        /,/,"

    )" << endl; //
        system("PAUSE");


        monsterhealth = 10;
        monsterdamage = 10;

        cout << "Ork Dies!\n\n";
        system("PAUSE");


        PlayerExperience += 25;
        PlayerMoney += 100;
cout << "Experience" << PlayerExperience << "--> " <<  endl;
cout << "Money" <<  PlayerMoney << "--> " << endl;
        arena();
    }
    else if(monster == 5)//
    {
        cout << "Fight a necromancer...\n\n";
         cout << R"(
              _,._
  .||,       /_ _\\
 \.`',/      |'L'| |
 = ,. =      | -,| L
 / || \    ,-'\"/,'`.
   ||     ,'   `,,. `.
   ,|____,' , ,;' \| |
  (3|\    _/|/'   _| |
   ||/,-''  | >-'' _,\\
   ||'      ==\ ,-'  ,'
   ||       |  V \ ,|
   ||       |    |` |
   ||       |    |   \
   ||       |    \    \
   ||       |     |    \
   ||       |      \_,-'
   ||       |___,,--")_\
   ||         |_|   ccc/
   ||        ccc/
    )" << endl; //
        system("PAUSE");


        monsterhealth = 10;
        monsterdamage = 10;

        cout << "Necromancer dies!\n\n";
        system("PAUSE");


        PlayerExperience += 25;
        PlayerMoney += 100;
cout << "Experience" << PlayerExperience << "--> " <<  endl;
cout << "Money" <<  PlayerMoney << "--> " << endl;
        arena();
    }
}

////EquipmentStore.h
#ifndef EQUIPMENTSTORE_H
#define EQUIPMENTSTORE_H
#include <string>
using namespace std;
#include "Mastermega.h"

class EquipmentStore: public Mastermega {
    public:
        void equip_store();
};

#endif
/////EquipmentStore.cpp

#include <iostream>
#include <cmath>
#include <climits>
#include <string>
using namespace std;
#include "EquipmentStore.h"
#include "Mastermega.h"

void EquipmentStore::equip_store()
{

    cout << "\n\n---Welcome to the Store--- \n\n\n";
    cout << "Your Gold: "<< PlayerMoney <<"\n\n";
    cout << "Weapons Available: \n\n";
    cout << "1)  Fire Staff +1: $40\n"; // Extra Damage: 1
    cout << "1)  Poison Staff +2: $50\n";  // Extra Damage: 2
    cout << "2)  Lightning Staff +3: $80\n";  // Extra Damage: 3
    cout << "3)  Ice Staff +4: $150\n\n";  // Extra Damage: 4

    cout << "Armor: \n\n";
    cout << "4)  +10 Armor: $50\n"; // Reduce damage to self by 5
    cout << "5)  +20 Armor: $100\n\n"; // Reduce damage to self by 10

    cout << "7) Play Menu: 7\n\n\n"; // Goes back to prior menu
    int menuchoice;
    cout << "Select an option: ";
    cin >>menuchoice;

    //balance check
    if(menuchoice == 1)
    {
        if(PlayerMoney < 40)
        {

            cout << "Sorry, you do not have enough Gold, return to play menu.";
            cin.get(); // Pause Screen
            mainmenu();
        }
    }
    else if(menuchoice == 2)
    {
        if(PlayerMoney < 50)
        {

            cout << "Sorry, you do not have enough Gold, return to play menu.";
            cin.get(); // Pause Screen
            mainmenu();
        }
    }
    else if(menuchoice == 3)
    {
        if(PlayerMoney < 80)
        {

            cout << "Sorry, you do not have enough Gold, return to play menu.";
            cin.get(); // Pause Screen
            mainmenu();
        }
    }
    else if(menuchoice == 4)
    {
        if(PlayerMoney < 150)
        {

            cout << "Sorry, you do not have enough Gold, return to play menu.";
            cin.get(); // Pause Screen
            mainmenu();
        }
    }
    else if(menuchoice == 5)
    {
        if(PlayerMoney < 50)
        {

            cout << "Sorry, you do not have enough Gold, return to play menu.";
            cin.get(); // Pause Screen
            mainmenu();
        }
    }
    else if(menuchoice == 6)
    {
        if(PlayerMoney < 100)
        {

            cout << "Sorry, you do not have enough Gold, return to play menu.";
            cin.get(); // Pause Screen
            mainmenu();
        }
    }

    if (menuchoice == 7)
    {

        cout << "Exit to Play Menu.\n\n";
        cin.get(); // Pause Screen


        mainmenu();
    }
    if(menuchoice == 1)
    {
        system("CLS");
        cout << "Fire Staff Purchased!\n\n";
        cin.get(); // Pause Screen
        system("CLS");

        PlayerMoney -= 40;//money is reduced
        PlayerWeapon = 2;//damage will be 2 from now on

        mainmenu();
    }
    else if(menuchoice == 2)
    {
        system("CLS");
        cout << "Poison Staff Purchased!\n\n";
        cin.get(); // Pause Screen
        system("CLS");

        PlayerMoney -= 50;
        PlayerWeapon = 3;

        mainmenu();
    }
    else if(menuchoice == 3)
    {
        system("CLS");
        cout << "Lightning Staff Purchased!\n\n";
        cin.get(); // Pause Screen
        system("CLS");

        PlayerMoney -= 80;
        PlayerWeapon = 4;

        mainmenu();
    }
    else if(menuchoice == 4)
    {
        system("CLS");
        cout << "Ice Staff Purchased!\n\n";
        cin.get(); // Pause Screen
        system("CLS");

        PlayerMoney -= 150;
        PlayerWeapon = 5;

        mainmenu();
    }
    else if(menuchoice == 5 || 6 )//armor
    {
        system("CLS");
        cout << "Armor Purchased!\n\n";
        cin.get(); // Pause Screen
        system("CLS");

        if(menuchoice == 5)
        {
            PlayerMoney -= 50;
            PlayerArmor += 5; // damage reduced by 2
        }
        else if(menuchoice == 6)
        {
            PlayerMoney -= 100;
            PlayerArmor += 10; //damage reduced by 5
        }

        mainmenu();
    }
}


What I have tried:

I have the program working, but need to modify it to use inheritance
Posted
Updated 16-Dec-21 10:47am

To be honest, I'm not going to go into details because that would mean a close inspection of that code, and what I can see from a cursory glance is that it's ... pretty poor quality. It's pretty much monolithic, it's full of duplicated code and "magic numbers", it's undocumented, and so forth. Don't get to depressed though - that's how we all started as students - it takes experience to learn how important it is to design code before we write it, and to write it with maintenance in mind.

Instead, let's talk about inheritance and how it's applied in general and let you work out how to apply it to your game.

Inheritance is just saying that this type of item is part of a bigger class: an "is a" relationship: An Orange is a CitrusFruit is a Fruit is a GrowsOnATree, a Lime is a CitrusFruit is a Fruit is a GrowsOnATree,while an Apple is a Fruit is a GrowsOnATree but not a CitrusFruit, and a Leaf is a GrowsOnATree but not a Fruit.

GrowsOnATree is the Base class for these, and Leaf & Fruit inherit from that class. Apple and CitrusFruit inherit from Fruit and so also inherit from GrowsOnATree. Orange & Lime both inherit from Citrus fruit and thus from everything it inherits.

But a Potato doesn't inherit from any of those: it doesn't grow on a tree so it can;t be handled by the same mechanisms: you can't implement a "Pick" method on a Potato, but you can for a Leat, Orange, Lime, or Apple - and you can't implement a "DigUp" method for any of those, but you need to for a Potato.

An "is a" relationship allow your to treat "inherited class" instances as if they where the parent class: you can have a bag of fruit and it can contain apples, oranges and limes - but not leaves! And you can define operations that need to be implemented (or can be defaulted) in the inherited class to perform operations that are generic to the parent class, but specific to the child: "Pick" for example is generic to the GrowsOnATree class, but requires different handling in Leaf class to that in the Fruit class - and a CitrusFruit can cope with rougher handling than an Apple which will bruise easily.

So to implement inheritance in your game isn't easy: you have to look at the object types in your game and identify which of them have a "is a" relationship. Then you can start working out a hierarchy of classes, and what properties go where, what functions each needs and where they should be defined or defaulted. A Chest for example is a Container which can contain other objects - Weapons, Food, Potions, Clothing, Armour, gold, ...
But not all of those will have a Sharpness, or a Damage; not all of those will have a Resistance, or a Value.

Basically, converting code from monolithic to object oriented isn't a case of "add inheritance" it needs a ground-up redesign to work at all.
 
Share this answer
 
Once you're finished converting this code to classes, you should have learned that you should design that way from the beginning. Rewriting the code later is a lot of work and is prone to error as you cut and paste fragments into various classes, or even rewrite some code from scratch.

After glancing through your code, I would suggest Game, Player, and Weapon as other classes, in addition to the Monster class already mentioned. There would only be one instance of Game, which would direct the overall program flow. There would be multiple instances of Player, which would be a base class if there were different types of players (e.g. warrior, wizard...). Similarly, Weapon would be a base class, with a derived class for each type of weapon.

One thing I noticed is that different weapons inflict different levels of damage on different monsters. This kind of two-dimensional dependency is something that is hard to implement cleanly: either each weapon must know about all types of monsters, or each monster must know about all types of weapons. It is common to use double dispatching[^] to handle this kind of situation, but I prefer to just use a two-dimensional array. That would work well here, because it's just a simple integer array: int Damage[MonsterId][WeaponId]. But I've even done this for complex state machines: EventHandlerId[StateId][EventId], the result of which indexes an array of EventHandler, each of which implements a HandleEvent function. But if the only thing you need to know about a weapon is how much damage it inflicts on each type of monster, Weapon would probably just be an enum instead of a class.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900