Weapon system with maps, is this the best way?

This is some code I came up with today, eventually I want to make a game and I found a cool way for a weapon system (setting a damage of a weapon, its attack speed etc..).

So theres multiple ways to approach a weapon system, you could create a base class called Weapon and make other classes maybe like Sword or Axe inherit from a weapon class. This would work, but would take a lot of time if you have 30-40 weapon (means 30-40 classes and .h + .cpp files).

So would if we created a map of weapon objects and set their variables there?

So we have our basic weapon class:

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
/*Weapon.h*/
#ifndef WEAPON_H
#define WEAPON_H
/*Weapon Class*/
class Weapon
{
	int damage = 0,attackSpeed = 0;
public:
	Weapon() = default;


	const int& getDamage()
	{
		return damage;
	}
	void setDamage(int set)
	{
		damage = set;
	}
	const int& getAttackSpeed()
	{
		return attackSpeed;
	}
	void setAttackSpeed(int set)
	{
		attackSpeed = set;
	}
};
#endif 


Ok great we have a weapon class,we can set and get the damage and attackspeed of each weapon. Now lets create a map of smart pointers to a weapon object.

1
2
3
4
5
6
        map<string, shared_ptr<Weapon>> weapons;
	weapons["Axe"] = make_shared<Weapon>();
	weapons["Axe"]->setDamage(10);
	weapons["Sword"] = make_shared<Weapon>();
	weapons["Sword"]->setDamage(20);
	cout << weapons["Axe"]->getDamage() << endl;


We can set the damage and attackspeed of each weapon, instead of a vector with elements we can use maps with a string to differentiate weapons making it easy to assign damage,attackspeed and whatever the hell you want. In addition because their smart pointers, it will free memory when it goes out of scope.

Would you guys say this is the ideal way to make a weapon system? Or is it better to make a class for every weapon or use a sequential container like Vectors? Any suggestions for improvements?
Last edited on
closed account (10X9216C)
I wouldn't use a map unless you plan on defining the weapons externally. As in you never actually have to do weapons["sword"] but you load a setting file for weapons and just do weapons[loadedName].

It is so easy mistype a string like that, and you won't know something is wrong til that line of code is run.
You said you have UE4? Means you have access to the UT source code. Check that out, particularly the AUTWeapon class:

https://github.com/EpicGames/UnrealTournament/blob/master/UnrealTournament/Source/UnrealTournament/Private/UTWeapon.cpp

And then the various AUTWeap_<Weapon> classes.

So as you can see, even the folks at Epic handle their weapons via some inheritance. You could use what they do as a template for your own code.
Topic archived. No new replies allowed.