[C++] How to build a game in C++?

Associate
Joined
18 Nov 2008
Posts
2,430
Location
Liverpool
Hi all, following my confusion in another thread of mine I feel like I need a bit of guidance before I delve any deeper into learning C++.

My intention in C++ is to build a game, but obviously not straight away. The game would include you the player as well as numerous different types of enemies (Think of something like Runescape for the purpose of the example).

The way I understood this to work was to have numerous classes, each representing a different enemy and each containing numerous variables (Hitpoints, weapons, name, damage bonuses for combat etc). However I've grown confused now that I'm putting it into practice. In terms of combat for example, the way I understood it to work was to reduce the remaining health of an enemy per attack, but how does this work if you only change the instance variable, does this not mean that at the start of every combat the enemy is returned to full health?

I'm just a bit confused on the basic structure of a game in C++, if anybody has any useful advice or tutorials in terms of this it would be great, I've had a Google round and followed a number of tutorials but each do things their own way, so I'm looking for a bit of personal experience.

Thanks very much!
 
Okay, in case it saves some time for somebody else to write, have I been looking at this the wrong way, are classes a way of determining the original variables of something, whereas for each actual use of the class you should use a separate array.

For example, the class declares that the starting HP of the player is always 100hp, then when you spawn the player, you assign that class variable to an array, that includes things like the players HP, the weapon he uses, and any other statistics?
 
why isn't the class instance (object) the player itself, and their HP a member variable of the player object?

you need to think in terms of nouns (classes), verbs (actions) and adjectives (properties)

get your terminology straight:

- class
- object
- method
- member variable

i'm presuming this question is related to a uni assignment...

a player is represented by a CLASS...THE player is an OBJECT INSTANCE of that class
 
Last edited:
Not sure how much help it will be, but have you checked out the source code to half life? It's freely available in the SDK for modding and will hopefully help you understand C++ processes.
 
Having read through this thread and your other one it appear you're a little confused as to how object oriented programming should work.

First off, developing a game in C++ as your first programming project seems a little ambitious.
Have you looked at XNA, or even something like ActionScript if you're really set on doing a game?

The way I understood this to work was to have numerous classes, each representing a different enemy and each containing numerous variables (Hitpoints, weapons, name, damage bonuses for combat etc).

This sounds about right, assuming you're talking about a class per enemy type and not a class per enemy instance.
It could possibly involve a class hierarchy of some sort, though you may not want to worry too much about that as part of your first piece of work.

However I've grown confused now that I'm putting it into practice. In terms of combat for example, the way I understood it to work was to reduce the remaining health of an enemy per attack, but how does this work if you only change the instance variable, does this not mean that at the start of every combat the enemy is returned to full health?

The object instance represents an enemy in this case. If you have 10 enemies you would have 10 instances.
Each one of them would get a default initial health (e.g. 100) and when you attack one of them it would reduce the health by a set amount.
Each instance maintains its own health level, so depending on who you attach you would have multiple instances each with different health levels.
An enemy is represented by the same instance for as long as it is alive, so you wouldn't get the situation of having the health return to full unless you coded it to do so.

Hope this makes some sort of sense to you.
 
I see where your understanding of this is going wrong but having an incredibly hard time working out how to explain it!

Each instance of a class is independant from any other instances of that same class.

There are no 'original' variables, each instance is treated the same and is responsible for itself. Maybe its easier if you think of it as having x amount of classes that are exactly the same?

If you have 10 instances of your enemy class and decrease the health of one, ONLY that instances health member variable will be modified, as they are separate objects.

Your enemy class might look something like this (.h):
(Remember to initialise your member variables somewhere either in a constructor or an initialise method or something!)

Class Enemy
{
public:
Enemy(void);
~Enemy(void);
void decreaseHealth(int damage)
void setHealth(int health);
void setPosition(Vector pos);
int getHealth();
Vector getPos();

private:
int _health;
Vector _position;
}

You should use get and set methods because public member variables are bad mmmmmmmmkay.

You then decide where in your program you want to create and initialise your enemies, and create a set of enemies like so:

Enemy enemies[10];

You could then decrease the health of an enemy by doing something like:

int damage = 5;
enemies[1].setHealth(enemies[1].getHealth - damage);

Hope this helps :)

P.s im still learning too so feel free to pick my post apart, advanced coders :P
 
Not sure how much help it will be, but have you checked out the source code to half life? It's freely available in the SDK for modding and will hopefully help you understand C++ processes.

Thanks for the advice! I'd heard so much about the source code to Half Life but never even considered looking at it for help on this subject, I'll get into that now :)

Having read through this thread and your other one it appear you're a little confused as to how object oriented programming should work.

First off, developing a game in C++ as your first programming project seems a little ambitious.
Have you looked at XNA, or even something like ActionScript if you're really set on doing a game?
I have done ActionScript and a derision of C to an extensive level, the problem is that I have never done anything in terms of making a game other than a few Java applet.


This sounds about right, assuming you're talking about a class per enemy type and not a class per enemy instance.
It could possibly involve a class hierarchy of some sort, though you may not want to worry too much about that as part of your first piece of work.

The object instance represents an enemy in this case. If you have 10 enemies you would have 10 instances.
Each one of them would get a default initial health (e.g. 100) and when you attack one of them it would reduce the health by a set amount.
Each instance maintains its own health level, so depending on who you attach you would have multiple instances each with different health levels.
An enemy is represented by the same instance for as long as it is alive, so you wouldn't get the situation of having the health return to full unless you coded it to do so.

Hope this makes some sort of sense to you.
Thank you, this is more or less what I thought in my second post but you've worded it a lot better!

Each instance of a class is independant from any other instances of that same class.

There are no 'original' variables, each instance is treated the same and is responsible for itself. Maybe its easier if you think of it as having x amount of classes that are exactly the same?

If you have 10 instances of your enemy class and decrease the health of one, ONLY that instances health member variable will be modified, as they are separate objects.

You should use get and set methods because public member variables are bad mmmmmmmmkay.

You then decide where in your program you want to create and initialise your enemies, and create a set of enemies like so:

Enemy enemies[10];

You could then decrease the health of an enemy by doing something like:

int damage = 5;
enemies[1].setHealth(enemies[1].getHealth - damage);

Hope this helps :)

P.s im still learning too so feel free to pick my post apart, advanced coders :P

Thanks for the advice and example, this is again more or less what I've done so it's certainly useful to get some form of confirmation, and I know what you mean about using get a set methods :)


Thanks for the advice and examples everyone! Very very useful for someone in my position and I really appreciate it :)!
 
Can I ask a question of the OP. Are you happy that you are ready for this kind of assignment/task ?

The questions indicate that there are quite a few concepts in C++ that you are not that familiar with.

Start with something really simple like a linked list class, then maybe a finite state machine and move on from there. These will allow you to get to grips with C++ before the complexity of the task overwhelms you.

Really, not trying to be patronising here, just recounting my own experiences.
 
Can I ask a question of the OP. Are you happy that you are ready for this kind of assignment/task ?

The questions indicate that there are quite a few concepts in C++ that you are not that familiar with.

Start with something really simple like a linked list class, then maybe a finite state machine and move on from there. These will allow you to get to grips with C++ before the complexity of the task overwhelms you.

Really, not trying to be patronising here, just recounting my own experiences.

Don't worry I know exactly what you mean, I've had a habit in the past of overwhelming myself with a new language and it really makes it difficult to continue.

At current I'm just doing a very small console based input / output system that includes classes. As this is almost done I'll be looking back to different areas of C++, I won't do anything big any time soon :)
 
Okay, while I'm on this road of research one other question related to the above.

In my main() I use Enemy enemies[10] to create multiple enemy instances. What I don't quite understand is that when I'm then in the Combat() method, I have to re-create these instances. So allow me to give you an example:

You begin combat with an enemy, it starts with 100hp and the combat is contained within the Combat() method. After a few attacks the enemy is down to 70hp, you then choose to exit the combat, thus ending the Combat() method. After a few moments you then decide to carry on the fight, this re-calls the Combat() method, effectively re-creating the instances, therefore resetting the hp of each instance to 100hp.

How do you stop this from happening? Is there a way if creating the instances in main() and transferring information regarding these instances to other methods?

Thanks!
 
Yes no problem, apologies for the mess, I've not been working with C++ long and I've yet to go through and remove the stuff that's no longer valid.

Code:
#include <iostream>
#include <cstring>
#include <ctime>
#include <stdio.h>
#include <cstdlib>

using namespace std;

int Combat ();
int getrand(int min, int max);
void PickAWeapon();

class Cow
{
    public:
        Cow();
        int HitPoints;
        void SetHitPoints ( int p );
        int GetHitPoints();
        string WeaponName;
        int WeaponBonus;
};
Cow::Cow()
{
    HitPoints = 100;
    WeaponName = "headbutt";
    WeaponBonus = 0;
}
void Cow::SetHitPoints ( int p )
{
  HitPoints = p;
}
int Cow::GetHitPoints()
{
  return HitPoints;
}

class Player
{
    private:
        static int WeaponBonus;
        static string WeaponName;
        static string PlayerName;
    public:
        Player();
        int HitPoints;
        void SetHitPoints ( int p );
        int GetHitPoints();
        static void setWeapon(int WepBonus, string WepName);
        static int getWeaponBonus();
        static string getWeaponName();
        static void setPlayerName(string PName);
        static string getPlayerName();
};
int Player::WeaponBonus = 0;
string Player::WeaponName = "Fists";
string Player::PlayerName = "Blank";
Player::Player()
{
    HitPoints = 150;
}
void Player::setWeapon(int WepBonus, string WepName)
{
	WeaponBonus = WepBonus;
	WeaponName = WepName;
}
void Player::setPlayerName(string PName)
{
	PlayerName = PName;
}
int Player::getWeaponBonus()
{
	return WeaponBonus;
}
string Player::getWeaponName()
{
	return WeaponName;
}
string Player::getPlayerName()
{
	return PlayerName;
}
void Player::SetHitPoints ( int p )
{
  HitPoints = p;
}
int Player::GetHitPoints()
{
  return HitPoints;
}

class Sword
{
    public:
        Sword();
        int AttackBonus;
};
Sword::Sword()
{
    AttackBonus = 10;
}

class Bat
{
    public:
        Bat();
        int AttackBonus;
};
Bat::Bat()
{
    AttackBonus = 5;
}

int main()
{
    Player player;
    cout<<"Welcome to my game, to begin, please enter your name: \n";
    string test;
    cin>>test;
    Player::setPlayerName(test);
    cin.ignore();
    srand(time(NULL));
    PickAWeapon();
    Cow cows[10];
    cows[0].SetHitPoints(50);
    Combat();
}

int Combat ()
{
    cout<<"\nWhat would you like to fight? Pick from a Cow or..well there's nothing else to fight so just pick Cow!\n";
    string response;
    getline (cin, response);
    if(response != "Cow")
    {
        cout<<"You have to fight something! Lets try this again...";
        Combat();
    }
    else
    {
        Player player;
        //Cow cow;
        Cow cows[10];
        int PHP = player.GetHitPoints();
        string PName = Player::getPlayerName();
        string PWeapon = Player::getWeaponName();
        int EHP = cows[0].GetHitPoints();
        string EName = response;
        string EWeapon = "headbutt";
        int Turn = 1;
        cout<<"\n"<<PName<<" and "<<EName<<" begin fighting...\n";
        while(PHP > 0 && EHP > 0)
        {
            if(Turn == 1)
            {
                int Damage = getrand(1,30);
                PHP -= Damage;
                if(PHP < 0)
                {
                    PHP = 0;
                }
                Turn = 2;
                cout<<EName<<" hit "<<PName<<" with "<<EWeapon<<" for "<<Damage<<" damage, "<<PName<<" has "<<PHP<<" health remaining.\n";
                cout<<"Press any key to continue\n";
                cin;
                cin.ignore();
            }
            if(Turn == 2)
            {
                int WepDamage = Player::getWeaponBonus();
                int Damage = getrand(1,(30+WepDamage));
                EHP -= Damage;
                if(EHP < 0)
                {
                    EHP = 0;
                }
                Turn = 1;
                cout<<PName<<" hit "<<EName<<" with "<<PWeapon<<" for "<<Damage<<" damage, "<<EName<<" has "<<EHP<<" health remaining.\n";
                cout<<"Press any key to continue\n";
                cin;
                cin.ignore();
            }

        }
        if(EHP == 0)//Cow Died
        {
            cout<<EName<<" has been defeated, congratulations "<<PName<<"!";
            cin;
            cin.ignore();
        }
        if(PHP == 0)//Player Died
        {
            cout<<"You died, you must be really **** lol";
            cin;
            cin.ignore();
        }
    }
}

int getrand(int min,int max)
{
    return(rand()%(max)+min);
}

void PickAWeapon()
{
    Player player;
    cout<<"\nWelcome to the armoury "<<Player::getPlayerName()<<", would you like a Sword, Bat, Shotgun or Nothing?\n";
    string response;
    getline (cin, response);
    if(response == "Sword")
    {
        Player::setWeapon(10,"Sword");
    }
    else if(response == "Bat")
    {
        Player::setWeapon(5,"Bat");
    }
    else if(response == "Shotgun")
    {
        Player::setWeapon(50,"Shotgun");
    }
    else if(response == "Nothing")
    {
        Player::setWeapon(0,"fists");
    }
    else
    {
        cout<<"Invalid Selection!\n";
        PickAWeapon();
    }
}
 
when you create your array of "enemies" (Cow cows[10]) in your main() method, it is being created local to the main() method because you're creating it on the stack

if you want to use the *same* array of "enemies" in your Combat() method you will need to pass it in as a parameter to the Combat() method, or make it global in scope (not good practice)

the best way is to pass a pointer to the array cows[10] to your Combat() method then your Combat() method will be working on the same array rather than a copy of it

research into "pass by value", "pass by reference" and pointers in C++
 
OP, you've done well so far and I like your enthusiasm :). But as a few others have said in this thread, I think you're jumping the gun a bit. How are you learning? Is this a uni project or a personal project? if personal, c# might be a better starting point for you.

If you're enjoying C++, slow down and get a book and work through it from the beginning. It'll take you through some very important stuff you need to know before you reach classes. Classes (object orientated programming) are important. Very important. But you're getting a bit ahead of yourself I think. Learn about pointers and references. They can be confusing at first but stick with them. Then you need to know about memory management and the difference between the stack and the heap.. Then maybe look at classes again.

Basically, learn from a book/examples on a website in an orderly fashion. I'm sorry I couldn't help you much more than this. I'd love to fix up your code and show you exactly how it works but there are important gaps in your knowledge that you need to address before you could understand it.

Keep the enthusiasm and remember we're always happy to help here :)
 
Back
Top Bottom