C++ enums with attributes like C# - c++

I have the following C# Code which I need to convert into C++ code. I have searched for a bit on how to do C++ Enums with Attributes and can not figure it out.
Basically I need a way to represent the following simplified C# Code in C++ which would do enums with attributes.
C# Code:
public class PSMNameAttribute : Attribute
{
public string PSMName;
public PSMNameAttribute(string _PSMName) { PSMName = _PSMName; }
}
public class PSMNumberAttribute : Attribute
{
public string PSMNumber;
public PSMNumberAttribute(string _PSMNumber) { PSMNumber = _PSMNumber; }
}
public class PSMNumberNameAttribute : Attribute
{
public string PSMNumberName;
public PSMNumberNameAttribute(string _PSMNumberName) { PSMNumberName = _PSMNumberName; }
}
public enum ShippingMethodsTypes
{
[PSMName("ErrorScriptMed")]
[PSMNumber("-5")]
[PSMNumberName("-5 ErrorScriptMed")]
ErrorScriptMed = -5
,
[PSMName("SpecialHandling")]
[PSMNumber("-1")]
[PSMNumberName("-1 SpecialHandling")]
SpecialHandling = -1
,
[PSMName("Error")]
[PSMNumber("0")]
[PSMNumberName("0 Error")]
Error = 0
}
Could this be done like this:
enum Category{
unknown = -1, meat, poultry, seafood, dairy, vegetable,fruit, grain, sweet
};
typedef struct {
float calories; // calories
float carbonhydrates; // grams
float fat; // grams
float cholesterol; // grams
float sodium; // grams
float protein; // grams
Category category ;
}Food;
and if so how would I call the struct values using the enum?

boost::variant and a few visitors should solve it nicely:
#include <boost/variant.hpp>
#include <iostream>
struct get_number : boost::static_visitor<int> {
template<class Method> int operator()(const Method& m) const { return number(m); }
};
struct get_name : boost::static_visitor<std::string> {
template<class Method> const std::string operator()(const Method& m) const { return name(m); }
};
struct ShippingMethodMed {};
static constexpr int number(ShippingMethodMed) { return -5; }
static std::string name(ShippingMethodMed) { return "ErrorScriptMedMed"; }
struct ShippingMethodSpecialHandling { };
static constexpr int number(ShippingMethodSpecialHandling) { return -10; }
static std::string name(ShippingMethodSpecialHandling) { return "SpecialHandling"; }
struct ShippingMethodError {};
static constexpr int number(ShippingMethodError) { return 0; }
static std::string name(ShippingMethodError) { return "Error"; }
using ShippingMethod = boost::variant<ShippingMethodMed, ShippingMethodSpecialHandling, ShippingMethodError>;
int number(ShippingMethod const& sm) {
return boost::apply_visitor(get_number(), sm);
}
std::string name(ShippingMethod const& sm) {
return boost::apply_visitor(get_name(), sm);
}
std::string number_name(ShippingMethod const& sm) {
return std::to_string(number(sm)) + " " + name(sm);
}
int main()
{
ShippingMethod m = ShippingMethodError();
std::cout << number(m) << std::endl;
std::cout << name(m) << std::endl;
std::cout << number_name(m) << std::endl;
m = ShippingMethodSpecialHandling();
std::cout << number(m) << std::endl;
std::cout << name(m) << std::endl;
std::cout << number_name(m) << std::endl;
}

This is not possible with enums alone.
However I think you could solve this by maintaining a string array/vector/map or a combination of those to your enum like:
enum test
{
first = 0,
second, // = 1
// etc...
};
const char* attributes[] =
{
"first attribute",
"second attribute",
};
then you could retrieve this attribute through
const char* firstattribute = attributes[test::first];

Related

How to handle polymorphism with vectors of a class the right way in C++?

I'm currently implementing an entity component system and working on a way to store vectors of components, each vector of one component type should be contiguous, this is why I'm using vector<Component>* and not vector<Component*>. I'm new to C++ and coming from Java, so I'm still struggling with some concepts regarding memory layout and polymorphism.
I've fully implemented a (seemingly) working version of this. I have a vector for each type of component there is (e.g. PositionComponent, GravityComponent, etc.), because components differ in size. But because the amount of types isn't known in compile time, I need a vector of pointers to point to these ComponentLists of different types. I'm using reinterpret_casts with a map which keeps track of the component types to accomplish this, but there has to be a less undefined way of doing this. (Hopefully!)
Here is a picture of what I want to achieve:
Component List Layout
Edit: I just notices that my program crashes with a segmentation fault after the return 0 in the main function. The call stack seems to be corrupted, as it jumps to some random address instead of actually returning. So my system is definately flawed.
Main function:
int main(int argc, char** argv)
{
EntityComponentSystem ecs;
// Fill with some components
for(int i = 0; i < 5; ++i)
{
ecs.addComponent(AComponent());
ecs.addComponent(BComponent());
ecs.addComponent(CComponent());
}
// Print all components
std::cout << "Components: " << std::endl;
// Print AComponents
std::cout << "A Components: " << std::endl;
ComponentList<AComponent>* aComps = ecs.getComponentList<AComponent>();
aComps->print();
// Print BComponents
std::cout << std::endl << "B Components: " << std::endl;
ComponentList<BComponent>* bComps = ecs.getComponentList<BComponent>();
bComps->print();
// Print CComponents
std::cout << std::endl << "C Components: " << std::endl;
ComponentList<CComponent>* cComps = ecs.getComponentList<CComponent>();
cComps->print();
return 0;
}
EntityComponentSystem class:
class EntityComponentSystem
{
private:
// To shorten some things up
typedef std::vector<ComponentList<Component>*>::iterator ComponentListIterator;
typedef std::unordered_map<std::type_index, Component::TypeID>::iterator MapIterator;
std::vector<ComponentList<Component>*> comps; // Indexed by TypeID
std::unordered_map<std::type_index, Component::TypeID> componentMap; // Maps typeid(Component) to TypeID
public:
EntityComponentSystem() : comps(), componentMap() {}
~EntityComponentSystem()
{
for(ComponentListIterator it = comps.begin(); it < comps.end(); ++it)
{
delete (*it);
}
}
template<typename T>
void addComponent(const T& component)
{
static_assert(std::is_base_of<Component, T>::value, "T must be of type Component!");
MapIterator found = componentMap.find(typeid(T));
ComponentList<T>* componentList = nullptr;
if(found == componentMap.end()) // This component derivative hasn't been added yet, so add it
{
componentList = new ComponentList<T>();
int componentId = comps.size();
this->comps.push_back(reinterpret_cast<ComponentList<Component>*>(componentList));
this->componentMap[typeid(T)] = componentId;
}
else
{
componentList = reinterpret_cast<ComponentList<T>*>(comps[found->second]);
}
componentList->push(component);
}
template<typename T>
ComponentList<T>* getComponentList()
{
Component::TypeID id = getComponentTypeId<T>();
if(id == Component::TYPE_ID_UNKNOWN) return nullptr;
return reinterpret_cast<ComponentList<T>*>(comps[id]);
}
template<typename T>
Component::TypeID getComponentTypeId()
{
static_assert(std::is_base_of<Component, T>::value, "T must be of type Component!");
MapIterator found = componentMap.find(typeid(T));
if(found == componentMap.end())
{
return Component::TYPE_ID_UNKNOWN;
}
return found->second;
}
};
ComponentList class:
template<typename T>
class ComponentList
{
private:
std::vector<T> components;
public:
void push(const T& t)
{
this->components.push_back(t);
}
void print()
{
for(typename std::vector<T>::iterator it = components.begin(); it != components.end(); ++it)
{
it->test();
}
}
};
Base Component class and its derivatives:
class Component
{
public:
typedef uint16_t TypeID;
static const TypeID TYPE_ID_UNKNOWN = -1;
virtual ~Component() = default;
virtual void test()
{
std::cout << "I'm the base!" << std::endl;
}
};
class AComponent : public Component
{
private:
static int nextValue;
int someValue; // To test if different sizes of Component derivatives cause any problems!
public:
AComponent()
{
this->someValue = nextValue++;
}
void test()
{
std::cout << "I'm AComponent! Value: " << someValue << std::endl;
}
};
int AComponent::nextValue = 0;
class BComponent : public Component
{
public:
void test()
{
std::cout << "I'm BComponent!" << std::endl;
}
};
class CComponent : public Component
{
public:
void test()
{
std::cout << "I'm CComponent!" << std::endl;
}
};

Make a collection of an abstract class type, Abstract Class vector of shared_ptr

Error
e/c++/v1/algorithm:642:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/utility:321:9: error:
field type 'Space' is an abstract class
_T2 second;
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/map:624:16: note:
Question
How can I define a std::vector of type Space which is an abstract class and then fill this vector with instances of the derived classes Empty, Snake, Ladder.
Context
I know abstract classes in C++ can not be instantiated. Instead I've read in several posts on this and other sites that you can create a collection of an abstract type if it the type is defined as a star * pointer or any of the <memory> managed pointer data types like std::unqiue_ptr<T>. I've tried to used shared_ptr<Space> in my case, but still unable to define the collection properly. I am compiled my code using g++ -std=c++17 main.cpp && ./a.out.
Code
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <map>
#include <memory>
#include <typeinfo>
#include <queue>
#include <string>
#include <vector>
class Player
{
private:
int m_current_space = 1;
public:
Player() {}
void role_dice() {
m_current_space += floor( (rand()%10 + 1) / 3 );
}
int const get_current_space() {
return m_current_space;
}
void set_current_space(int current_space) {
m_current_space = current_space;
}
};
class Space
{
protected:
int m_id;
std::vector<Space> m_paths;
public:
Space() {} // requied to use [] operator in map
Space(int id) : m_id(id) {}
void add_path(Space& s) {
m_paths.push_back(s);
}
int get_id() {
return m_id;
}
virtual std::string class_type() = 0;
};
class Empty : public Space
{
public:
Empty(int id) : Space(id) {}
std::string class_type() {
return "Empty";
}
};
class Ladder : public Space
{
public:
Ladder(int id) : Space(id) {}
virtual void event(Player& p) {
p.set_current_space(1);
}
std::string class_type() {
return "Ladder";
}
};
class Snake : public Space
{
public:
Snake(int id) : Space(id) {}
virtual void event(Player& p) {
p.set_current_space(4);
}
std::string class_type() {
return "Snake";
}
};
class Board
{
private:
std::map<int, Space> m_board;
public:
void add_space(Space& s) {
m_board[s.get_id()] = s;
}
void draw_board() {
int i = 1;
for(auto const& [space_key, space] : m_board) {
if(i%3 == 0) {
std::cout << "○\n";
}
else if(typeid(space) == typeid(Snake)) {
std::cout << "○-";
}
else {
std::cout << "○ ";
}
++i;
}
}
void update_player_on_board(int position) {
int i = 1;
for(auto const& [space_key, space] : m_board) {
if(i%3 == 0) {
if (space_key == position) {
std::cout << "●\n";
}
else {
std::cout << "○\n";
}
}
else if(typeid(space) == typeid(Snake)) {
std::cout << "○-";
}
else {
if (space_key == position) {
std::cout << "● ";
}
else {
std::cout << "○ ";
}
}
++i;
}
}
const std::map<int, Space> get_board() {
return m_board;
}
friend std::ostream &operator<<(std::ostream& os, const Board& b) {
return os;
}
};
class GameStateManager
{
private:
std::string m_state = "game over";
bool m_playing = false;
public:
std::string const get_state() {
return m_state;
}
void set_state(std::string state) {
m_state = state;
}
};
int main()
{
std::cout << "Welcome to Bowser's 9 board game\n";
std::cout << "Start? y(yes) n(no)\n";
GameStateManager game_manager;
game_manager.set_state("playing");
auto space1 = std::make_shared<Space>(1);
auto space2 = std::make_shared<Space>(2);
auto space3 = std::make_shared<Space>(3);
auto space4 = std::make_shared<Space>(4);
auto space5 = std::make_shared<Space>(5);
auto space6 = std::make_shared<Space>(6);
auto space7 = std::make_shared<Space>(7);
auto space8 = std::make_shared<Space>(8);
auto space9 = std::make_shared<Space>(9);
std::vector<std::shared_ptr<Space>> v {
space1, space2, space3,
space4, space5, space6,
space7, space8, space9
};
Board bowsers_bigbad_laddersnake;
for(int i = 0; i < 10; ++i) {
bowsers_bigbad_laddersnake.add_space(*(v[i]));
}
bowsers_bigbad_laddersnake.draw_board();
Player mario;
int turn = 0;
while(game_manager.get_state() == "playing") {
std::cin.get();
std::cout << "-- Turn " << ++turn << " --" << '\n';
mario.role_dice();
bowsers_bigbad_laddersnake.update_player_on_board(mario.get_current_space());
if (mario.get_current_space() >= 9) {
game_manager.set_state("game over");
}
}
std::cout << "Thanks a so much for to playing!\nPress any key to continue . . .\n";
std::cin.get();
return 0;
}
You seem to have removed a lot of code to get into details here.
Have a Space pointer (smart or raw). Instantiate the specific space that you want, point to it with your pointer of type Space. Example std::shared_ptr<Space> pointerToSpace = std::make_shared<Snake> ("I'm a snake"); Now, without loss of generality, you can print the contents (of concrete type) with just the pointer to the space pointerToSpace->class_type(). Yes, you can have a collection of shared_ptrs in a container.

Inheritance , how can i make two classes share the same base class contents?

I have an Abstract Class operations that inherits from VAR Class , which then all the operations derived class(out,sleep,Add) inherit from the operations class. FSM Class inherits from Var also, so That I want one instance of VAR class inside my program.
I am trying to make vector < pair< string, int>> var as a shared data between the FSM class and the Operations class and its deviates . I initialized the var in the main through the FSM class .
Each time we call the exist function in VAR through Class operation , it returns it doesn't exits cause it is empty ! How can I overcome this?
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
class VAR
{
public:
vector<pair<string, int>> var;
VAR()
{
cout << "created VAR" << endl;
}
~VAR(){ cout << "Destrioed VAR" << endl; }
void createVar(string x,int y)
{
pair<string, int>t;
t.first = x;
t.second = y;
var.push_back(t);
}
int getVarValue(string x)
{
for (int i = 0; i<var.size(); i++)
{
if (var[i].first == x)
{
return var[i].second;
}
}
}
void setVarValue(string& x, int y)
{
for (int i = 0; i<var.size(); i++)
{
if (var[i].first == x)
{
var[i].second = y;
i = var.size();
}
}
}
bool exits(string& name)
{
for (int i = 0; i<var.size(); i++)
{
if (var[i].first == name)
return true;
}
return false;
}
};
class operations : virtual public VAR
{
public:
operations()
{
cout << "operations created" << endl;
}
~operations()
{
cout << "operations Destroied" << endl;
}
void virtual excute() = 0;
};
class Out :public virtual operations
{
public:
string s;
Out(string xx = "") :s(xx)
{
cout << "Out created" << endl;
}
~Out()
{
cout << "Out Destroied" << endl;
}
void virtual excute()
{
cout << "out Class" << endl;
if (exits(s))
cout<<"it never reach here, WHY !"<<endl;
}
};
class Add :public virtual operations
{
public:
string s;
Add(string ss = "") :s(ss)
{
cout << "ADD created" << endl;
}
~Add()
{
cout << "Add Destroied" << endl;
}
void virtual excute()
{
string ex1 = s.substr(s.find('=') + 1, s.find('+')), ex2 = s.substr(s.find('+') + 1);
if (exits(ex1))
cout<<"it never reach here, WHY !"<<endl;
else
result = atoi(ex1.c_str());
if (exits(ex2))
cout<<"it never reach here, WHY !"<<endl;
}
};
class state
{
public:
vector<operations*> instructionList;
string name;
void exec_all()
{
for (int x = 0; x < instructionList.size(); x++)
instructionList[x]->excute();
}
};
class transition
{
public:
vector < pair<state, vector<pair<state, int>>>> trans;
static int currentState;
};
class FSM :public virtual VAR, public virtual transition
{
public:
FSM()
{
cout << "FSM" << endl;
}
void intialize()
{
createVar("X", 1);
createVar("Y", 5);
}
};
void main()
{
FSM x;
pair<state, vector<pair<state, int>>> p1;
pair<state, int>p2;
x.intialize();
p2.first.name = "b";
p2.second = 3;
p1.first.name = "a";
p1.second.push_back(p2);
x.trans.push_back(p1);
x.trans[0].first.instructionList.push_back(new Add("X=X+Y"));
x.trans[0].first.instructionList.push_back(new Out("X"));
x.trans[0].first.exec_all();//wrong output cause exist() returns false
}
A minimal complete example looks something like this:
#include <iostream>
using namespace std;
class VAR
{
public:
int var;
virtual ~VAR()
{}
void setVar(int n)
{var=n;}
};
class Out :public VAR
{};
class FSM :public VAR
{};
int main()
{
FSM x;
x.setVar(5);
Out OP;
if (x.var==OP.var)
cout<<"it reaches here now" << endl;
else
cout << "it fails" << endl;
return(0);
}
And one way to fix it is like this:
class VAR
{
public:
static int var;
int var;
virtual ~VAR()
{}
void setVar(int n)
{var=n;}
};
int VAR::var=0;

Policy based design - policy implementation has to access members of the host class

I think the best way to explain my question is with a piece of code:
class IncreasingMultiplier {
protected:
IncreasingMultiplier(int initialMultiplier = 0, int incrementation = 1)
int getMultiplier() {
mCurrentMultiplier += mIncrementation;
return mCurrentMultiplier - mIncrementation;
}
void setMultiplier(int multiplier) {
mCurrentMultiplier = multiplier;
}
void setIncrementation(int incrementation) {
mIncrementation = incrementation;
}
private:
int mCurrentMultiplier;
int mIncrementation;`
}
class ConstMultiplier {
protected:
int getMultiplier() const {
return 10;
}
}
class NumberLogger {
public:
void log() {
int currentNumber = getNumber(); // How can I call this method?
std::cout << "Current number is " << currentNumber << std::endl;
}
}
template<
class MultiplierPolicy,
class LoggingPolicy
>
class Host : public MultiplierPolicy, public LoggingPolicy {
public:
int getNumber() const {
return mNumber * getMultiplier();
}
private:
int mNumber;
}
Basically, one policy may need to access members defined in the host class, which are in turn dependent on other policies supplied to the host class.
Thanks!
The following code compiles with VS2013 (have not tried with GCC):
#include <iostream>
class IncreasingMultiplier {
protected:
IncreasingMultiplier(int initialMultiplier = 0, int incrementation = 1)
: mCurrentMultiplier(initialMultiplier)
, mIncrementation(incrementation)
{}
int getMultiplier() {
mCurrentMultiplier += mIncrementation;
return mCurrentMultiplier - mIncrementation;
}
void setMultiplier(int multiplier) {
mCurrentMultiplier = multiplier;
}
void setIncrementation(int incrementation) {
mIncrementation = incrementation;
}
private:
int mCurrentMultiplier;
int mIncrementation;
};
class ConstMultiplier {
protected:
int getMultiplier() const {
return 10;
}
};
// Template the logger policy
// Unfortunately - couldn't get host inheritance CRTP pattern
// compiling in Visual Studio 2013 :(
// https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
template < typename t_Host >
class NumberLogger /*: public t_Host*/ {
public:
void log() {
// This part of the CRTP pattern does work in Visual Studio 2013
int currentNumber = static_cast<t_Host*>(this)->getNumber(); // How can I call this method?
std::cout << "Current number is " << currentNumber << std::endl;
}
};
// Template based on a list of policies
template<
typename PoliciesList
>
class Host : public PoliciesList::MultiplierPolicy, public PoliciesList::LoggingPolicy {
public:
Host() : mNumber(1) {}
int getNumber() /*const*/ {
return mNumber * getMultiplier();
}
private:
int mNumber;
};
// Un-templated policies list
// Could create a macro to declare various policy combinations:
class ConcretePoliciesList_Const
{
public:
typedef Host<ConcretePoliciesList_Const> MyHost;
typedef ConstMultiplier MultiplierPolicy;
typedef NumberLogger<MyHost> LoggingPolicy;
};
class ConcretePoliciesList_Increasing
{
public:
typedef Host<ConcretePoliciesList_Increasing> MyHost;
typedef IncreasingMultiplier MultiplierPolicy;
typedef NumberLogger<MyHost> LoggingPolicy;
};
int main()
{
ConcretePoliciesList_Const::MyHost const_host;
ConcretePoliciesList_Increasing::MyHost increasing_host;
std::cout << "Const policy:" << std::endl;
const_host.log();
const_host.log();
const_host.log();
std::cout << "Increasing policy:" << std::endl;
increasing_host.log();
increasing_host.log();
increasing_host.log();
return 0;
}
The resulting output is:
Const policy:
Current number is 10
Current number is 10
Current number is 10
Increasing policy
Current number is 0
Current number is 1
Current number is 2

Copying object from a superclass pointer

Suppose I have two classes a base class and an inherited class as follows:
class Magic : public Attack
{
public:
Magic(int uID, std::string &name) : Attack(ActionType::MagicAction, uID, name)
{
}
};
class MacroMagic : public Magic
{
MacroMagic(int uID) : Magic(uID, std::string("Testing"))
{
}
void PreUse() override
{
std::cout << "Test" << std::endl;
}
}
I have a shared_ptr to an instance of magic that I would like to copy, but at runtime I will not know whether that pointer points to an instance of Magic, MacroMagic or anything that may have inherited from Magic. I want to be able to copy the object pointed to by the shared_ptr like so:
Battles::magic_ptr mgPtr = MagicNameMap[name];
if (mgPtr.get() != nullptr)
{
return magic_ptr(new Magic(*mgPtr));
}
return mgPtr;
where magic_ptr is a typedef for a shared_ptr around the Magic Class. I could do it by specifying a virtual copy function and calling that, but I'd like to make it less obtuse and easier to maintain. I assume I can do this by a copy constructor, but I'm unsure how to in this instance. The way I have it now, the pointer returned by the above code will not call the override pReUse() function.
A bit of guidance would be much appreciated, thanks
I could do it by specifying a virtual copy function and calling that, but I'd like to make it less obtuse and easier to maintain.
you're working against the language.
you could accomplish what you are after, but i don't recommend it, and it is certainly not easier to setup or maintain than virtual Magic* clone() = 0.
perhaps you could outline the problem that brought you to this conclusion, and then we can help from there. there are usually alternatives which don't fight the language.
EDIT
here's a way around it using an external function table (t_magic_operation_table). you can apply and create several function tables and keep them around. since they exist in the magic object as a single pointer, then you can make these tables quite large (if needed). if your magic types can use the same data/members, then that is one approach. be careful: i threw this together suuuper-fast. it demonstrates the technique, but it's pretty bad otherwise:
#include <iostream>
#include <string>
namespace MONSpiel {
inline unsigned prndm(const unsigned& max) {
return 1 + arc4random() % max;
}
class t_ghoul;
class t_biclops;
class t_magic;
class t_hero {
t_hero();
t_hero(const t_hero&);
t_hero& operator=(const t_hero&);
public:
t_hero(const std::string& inName) : d_name(inName) {
}
const std::string& name() const {
return this->d_name;
}
template<typename TEnemy, typename TMagic>
void attack(TEnemy& enemy, TMagic& magic) const {
if (enemy.isDead()) {
return;
}
enemy.hit(magic.power());
if (enemy.isDead()) {
std::cout << this->name() << ": see you in the prequel...\n\n";
}
else {
std::cout << this->name() << ": have you had enough " << magic.name() << ", " << enemy.name() << "???\n\n";
}
}
/* ... */
private:
const std::string d_name;
};
class t_enemy {
t_enemy();
t_enemy(const t_enemy&);
t_enemy& operator=(const t_enemy&);
public:
t_enemy(const std::string& inName) : d_name(inName), d_lifePoints(1000) {
}
virtual ~t_enemy() {
}
const std::string& name() const {
return this->d_name;
}
bool isDead() const {
return 0 >= this->d_lifePoints;
}
const int& lifePoints() const {
return this->d_lifePoints;
}
void hit(const int& points) {
this->d_lifePoints -= points;
}
/* ... */
private:
const std::string d_name;
int d_lifePoints;
};
class t_ghoul : public t_enemy {
public:
static int MaxDaysAwake() {
return 100;
}
t_ghoul(const std::string& inName) : t_enemy(inName), d_bouyancy(prndm(100)), d_proximityToZebra(prndm(100)), d_daysAwake(prndm(MaxDaysAwake())) {
}
const int& bouyancy() const {
return this->d_bouyancy;
}
const int& proximityToZebra() const {
return this->d_proximityToZebra;
}
const int& daysAwake() const {
return this->d_daysAwake;
}
private:
int d_bouyancy;
int d_proximityToZebra;
int d_daysAwake;
};
class t_biclops : public t_enemy {
public:
t_biclops(const std::string& inName) : t_enemy(inName), d_isTethered(prndm(2)), d_amountOfSunblockApplied(prndm(100)) {
}
const bool& isTethered() const {
return this->d_isTethered;
}
const int& amountOfSunblockApplied() const {
return this->d_amountOfSunblockApplied;
}
private:
bool d_isTethered;
int d_amountOfSunblockApplied;
};
class t_magic_operation_table {
public:
typedef void (*t_ghoul_skirmish_function)(t_magic&, t_ghoul&);
typedef void (*t_biclops_skirmish_function)(t_magic&, t_biclops&);
t_magic_operation_table(t_ghoul_skirmish_function ghoulAttack, t_biclops_skirmish_function biclopsAttack) : d_ghoulAttack(ghoulAttack), d_biclopsAttack(biclopsAttack) {
}
void willSkirmish(t_magic& magic, t_ghoul& ghoul) const {
this->d_ghoulAttack(magic, ghoul);
}
void willSkirmish(t_magic& magic, t_biclops& biclops) const {
this->d_biclopsAttack(magic, biclops);
}
private:
t_ghoul_skirmish_function d_ghoulAttack;
t_biclops_skirmish_function d_biclopsAttack;
};
class t_action {
public:
typedef enum t_type {
NoAction = 0,
MagicAction,
ClubAction,
ClassAction
} t_type;
};
class t_attack {
public:
t_attack(const t_action::t_type& actionType, const int& uID, const std::string& inName) : d_actionType(actionType), d_uID(uID), d_name(inName) {
}
virtual ~t_attack() {
}
void reset() {
/* ... */
}
const std::string& name() const {
return this->d_name;
}
private:
t_action::t_type d_actionType;
int d_uID;
std::string d_name;
};
class t_magic : public t_attack {
t_magic();
t_magic(const t_magic&);
t_magic& operator=(const t_magic&);
static void GhoulSkirmishA(t_magic& magic, t_ghoul& ghoul) {
magic.d_accuracy = ghoul.bouyancy() + prndm(16);
magic.d_power = ghoul.proximityToZebra() + prndm(43);
}
static void GhoulSkirmishB(t_magic& magic, t_ghoul& ghoul) {
magic.d_accuracy = ghoul.bouyancy() / magic.flammability() + prndm(32);
magic.d_power = t_ghoul::MaxDaysAwake() - ghoul.daysAwake() + prndm(23);
}
static void BiclopsSkirmishA(t_magic& magic, t_biclops& biclops) {
if (biclops.isTethered()) {
magic.d_accuracy = 90 + prndm(16);
}
else {
magic.d_accuracy = 40 + prndm(11);
}
magic.d_power = biclops.amountOfSunblockApplied() + prndm(17);
}
static void BiclopsSkirmishB(t_magic& magic, t_biclops& biclops) {
if (biclops.isTethered()) {
magic.d_accuracy = 80 + prndm(80);
}
else {
magic.d_accuracy = 50 + prndm(50);
}
magic.d_power = 80 + prndm(30);
}
const t_magic_operation_table* NextOperationTable() {
static const t_magic_operation_table tables[4] = {
t_magic_operation_table(GhoulSkirmishA, BiclopsSkirmishA),
t_magic_operation_table(GhoulSkirmishB, BiclopsSkirmishB),
t_magic_operation_table(GhoulSkirmishB, BiclopsSkirmishA),
t_magic_operation_table(GhoulSkirmishA, BiclopsSkirmishB)
};
return & tables[arc4random() % 4];
}
public:
t_magic(const int& uID, const std::string& inName) : t_attack(t_action::MagicAction, uID, inName), d_power(-1), d_accuracy(-1), d_operationTable(0) {
}
int flammability() const {
return prndm(73);
}
int power() const {
return this->d_power;
}
void reset() {
t_attack::reset();
this->d_power = -1;
this->d_accuracy = -1;
this->d_operationTable = 0;
}
private:
/* assigns this->d_operationTable */
void updateOperationTableForAttack() {
this->d_operationTable = NextOperationTable();
}
public:
void heroWillAttack(const t_hero& hero, t_ghoul& ghoul) {
this->updateOperationTableForAttack();
this->d_operationTable->willSkirmish(*this, ghoul);
std::cout << hero.name() << " vs. " << ghoul.name() << "(lp:" << ghoul.lifePoints() << ")";
this->printState();
}
void heroWillAttack(const t_hero& hero, t_biclops& biclops) {
this->updateOperationTableForAttack();
this->d_operationTable->willSkirmish(*this, biclops);
std::cout << hero.name() << " vs. " << biclops.name() << "(lp:" << biclops.lifePoints() << ")";
this->printState();
}
void printState() {
std::cout << ": Magic { Power: " << this->d_power << ", Accuracy: " << this->d_accuracy << ", Operation Table: " << this->d_operationTable << "}\n";
}
private:
int d_power;
int d_accuracy;
const t_magic_operation_table* d_operationTable;
};
template<typename TEnemy>
void AttackEnemyWithMagic(t_hero& hero, TEnemy& enemy, t_magic& magic) {
if (!enemy.isDead()) {
magic.heroWillAttack(hero, enemy);
hero.attack(enemy, magic);
magic.reset();
}
}
inline void PlayIt() {
t_hero zoe("Zoe");
t_hero aragosta("Aragosta");
t_ghoul ghoul0("Al Paca");
t_ghoul ghoul1("Spud");
t_ghoul ghoul2("Sleepy");
t_biclops biclops("Scimpanzè");
t_magic hemlock(59, "hemlock");
t_magic babyPowder(91, "baby powder");
for (size_t idx(0); idx < 1000; ++idx) {
AttackEnemyWithMagic(zoe, ghoul1, hemlock);
AttackEnemyWithMagic(aragosta, biclops, babyPowder);
AttackEnemyWithMagic(zoe, ghoul2, hemlock);
AttackEnemyWithMagic(aragosta, ghoul0, babyPowder);
}
}
} /* << MONSpiel */
int main(int argc, char* const argv[]) {
#pragma unused(argc)
#pragma unused(argv)
MONSpiel::PlayIt();
return 0;
}
another option is to simply create stores (e.g. a vector), each with a different magic type. then fill a vector to point to objects in those stores. that way, you can just create one contiguous allocation for each type and randomize and weigh as needed. this is useful if your magic objects' sizes vary considerably.