将二维数组中的值分配给类

时间:2021-05-26 22:30:15

标签: c++

我正在制作一个文本游戏,我希望为玩家或怪物分配武器。 我创建了一个具有最小和最大伤害的二维数组,因此我可以在最小/最大之间随机化每次命中。

但我现在被困住了。
我应该在武器类中集成二维数组吗?
如何影响每个玩家的武器?

感谢您的帮助:)

#include <iostream>

class player{
public:
    std::string playerName;
    int health; 
    int maxmana;
    int minDegatWeapon;
    int maxDegatWeapon;
};

class weapon{
public:
    std::string weaponName;
    int maxDegatWeapon;
    int minDegatWeapon;
};

void createPlayer(player *p, weapon *w){
    int weaponSelection = 0;
    std::cout << "Player Name ?\n";
    std::getline (std::cin,p->playerName);
    p->health = 20;
    p->maxmana = 80;
    std::cout << "Choose your Weapon : 1-Dagger / 2-Sword / 3-Axe ? \n";
    std::cin >> weaponSelection;
};

int main(){

    player human = {" ", 0, 0, 0, 0};
    weapon humanWeapon = {" ", 0, 0};

int weapons[3][2] = {
    {3,4}, //dagger
    {1,6}, //sword
    {0,7} //axe
};

    createPlayer(&human, &humanWeapon);

    return 0;
}

1 个答案:

答案 0 :(得分:1)

您始终可以将 class Weapon 设为抽象类。没有“通用武器”,因此实例化武器类型的对象是不合适的。相反,让多个类从武器类继承,并根据需要调整它们的最小值/最大值。此外,您可以通过在 Player 类中添加武器来将此武器分配给玩家。

#include <random>
#include <time.h>
class Weapon
{
public:
  virtual std::string getWeaponType() = 0;
  virtual int generateDamage() = 0;
  int minDmg, maxDmg;
};

class Sword : public Weapon
{
public:
  Sword()
  {
    minDmg = 1;
    maxDmg = 6;
  }
  std::string getWeaponType()
  {
    return "SWORD";
  }
  int generateDamage()
  {
    return ( rand() % maxDmg + minDmg );
  }
};

class Player
{
public:
  Player(int weapon)
  {
    if(weapon == 1)
    {
       w = new Sword();
    }
    //else if(weapon == 2).....
    //..................
  }
  Weapon* getWeapon()
  {
    return w;
  }
private:
  Weapon* w;
};

int main()
{
  srand(time(NULL)); //random seed
  Player p1 = Player(1);
  std::cout << p1.getWeapon().generateDamage() << '\n'; //see if it works
}
相关问题