问题描述
我正在尝试使用C ++创建D&D战斗遭遇模拟器,并且由于它是D&D,因此模拟的所有方面都将严重依赖于“ Dice”类及其方法。 每当另一个类需要时,我都可以实例化“ Dice”对象 调用它的方法,但是,这将使一切沉重 耦合,以后很难进行更改或扩展。
我对工厂,依赖注入和其他此类方法没有任何实践知识。 因此,我的问题本质上是:
什么是确保“ Dice”类保留为 尽可能与所有其他班级脱钩? 在需要时仍允许他们使用“骰子”对象及其方法。
Dice.h
#ifndef dice_h_
#define dice_h_
#include <stdlib.h>
class Dice
{
private:
int maxValue;
public:
Dice(int maxValue);
~Dice();
int getMaxValue( void ){return maxValue;}
void setMaxValue(int newMaxValue){maxValue = newMaxValue;}
int rollDice();
int rollMultipleDice(int numberOfDiceRolls);
};
#endif
Dice.cpp
#ifndef dice_cpp_
#define dice_cpp_
#include "dice.h"
Dice::Dice(int maxValue){this->maxValue = maxValue;}
Dice::~Dice(){}
int Dice::rollDice()
{
return (rand() % maxValue) + 1;
}
int Dice::rollMultipleDice(int numberOfDiceRolls)
{
int i = numberOfDiceRolls,sum = 0;
while(i-- > 0)
{
sum += rollDice();
}
return sum;
}
#endif
Actor.h
#ifndef actor_h_
#define actor_h_
#include "dice.h"
class Actor
{
private:
unsigned int hp;
unsigned int ac; // Armor Class
unsigned int dmg;
public:
Actor(unsigned int hp,unsigned int ac,unsigned int dmg);
~Actor();
unsigned int getHP( void );
unsigned int getAC( void );
unsigned int getDmg( void );
void setHP( unsigned int newHP);
void setAC( unsigned int newAC);
void setDmg( unsigned int newDmg);
void attack(Actor* target);
bool isHit(Actor target);
};
#endif
Actor.cpp
#ifndef actor_cpp_
#define actor_cpp_
#include "actor.h"
Actor::Actor(unsigned int hp,unsigned int dmg)
{
this->hp = hp;
this->ac = ac;
this->dmg = dmg;
}
Actor::~Actor(){}
unsigned int Actor::getHP( void ){return hp;}
unsigned int Actor::getAC( void ){return ac;}
unsigned int Actor::getDmg( void ){return dmg;}
void Actor::setHP( unsigned int newHP ){this->hp = newHP;}
void Actor::setAC( unsigned int newAC ){this->ac = newAC;}
void Actor::setDmg( unsigned int newDmg ){this->dmg = newDmg;}
void Actor::attack(Actor* target)
{
Dice damageDice(8);
if (isHit(*target))
{
target->setHP(target->getHP() - damageDice.rollDice());
}
}
// helper function to attack function
// do not use elsewhere
bool Actor::isHit(Actor target)
{
Dice atkDice(20);
return atkDice.rollDice() >= target.getAC();
}
#endif
解决方法
您在问题中谈论单例之类的东西,那么您是否想让需要使用骰子的类使用Dice类的相同实例?
如果是这样,因为Dice类没有任何要保留的状态,可以是静态类。然后,我将删除MaxValue并将输入添加到RollDice和RollMutiDice以获取Max Value(我猜这是假设到骰子的“边”)。因此,对Dice :: RollDice(3)的调用是掷出一个3面的骰子,或者Dice :: RollMutiDice(6,3)会掷出一个6面的骰子3次。
还要确保发送rand()类。我认为是srand(int)。通常您会花时间,所以它是随机的