Могу ли я конденсировать различные объявления нескольких классов?

#c

Вопрос:

Я создаю систему добычи DnD и у меня есть класс

 class RPGItem
{
public:
    string name, type, rarity, description;
    bool attunement = true;
};
 

Я хочу, чтобы массив содержал все независимые экземпляры класса. Чтобы я мог вытащить и распечатать каждый из них на основе интергера. Однако в настоящее время это выглядит ужасно всего с пятью предметами, и я хотел бы знать, могу ли я как-то сгладить это.

     RPGItem StoredItems[5];

    StoredItems[0].name = "Longsword  1";
    StoredItems[0].type = "Weapon";
    StoredItems[0].rarity = "Unncommon";
    StoredItems[0].attunement = false;
    StoredItems[0].description = "You have a  1 bonus to attack and damage rolls made with this magic weapon.";

    StoredItems[1].name = "Amulet of Health";
    StoredItems[1].type = "Wondrous Item";
    StoredItems[1].rarity = "Rare";
    StoredItems[1].attunement = true;
    StoredItems[1].description = "Your Constitution score is 19 while you wear this amulet. It has no effect on you if your Constitution is already 19 or higher without it.";

    StoredItems[2].name = "Dust of Dryness";
    StoredItems[2].type = "Wonderous Item";
    StoredItems[2].rarity = "Uncommon";
    StoredItems[2].attunement = false;
    StoredItems[2].description = "This small packet contains 1d6   4 pinches of dust. You can use an action to sprinkle a pinch of it over water. The dust turns a cube of water 15 feet on a side into one marble-sized pellet, which floats or rests near where the dust was sprinkled. The pellet's weight is negligible. Someone can use an action to smash the pellet against a hard surface, causing the pellet to shatterand release the water the dust absorbed. Doing so ends that pellet's magic. An elemental composed mostly of water that is exposed to a pinch of the dust must make a DC 13 Constitution saving throw, taking 10d6 necrotic damage on a failed save, or half as much damage on a successful one.";

    StoredItems[3].name = "Nine Lives Stealer";
    StoredItems[3].type = "Weapon (any sword)";
    StoredItems[3].rarity = "Very Rare";
    StoredItems[3].attunement = true;
    StoredItems[3].description = "You gain a  2 bonus to attack and damage rolls made with this magic weapon. The sword has 1d8   1 charges. If you score a critical hit against a creature that has fewer than 100 hit points, it must succeed on a DC 15 Constitution saving throw or be slain instantly as the sword tears its life force from its body(a construct or an undead is immune). The sword loses 1 charge if the creature is slain. When the sword has no charges remaining, it loses this property.";

    StoredItems[4].name = "Ring of Animal Influence";
    StoredItems[4].type = "Ring";
    StoredItems[4].rarity = "Rare";
    StoredItems[4].attunement = false;
    StoredItems[4].description = "This ring has 3 charges, and it regains 1d3 expended charges daily at dawn. While wearing the ring, you can use an action to expend 1 of its charges to cast one of the following spells:nAnimal friendship(save DC 13)nFear(save DC 13), targeting only beasts that have an Intelligence of 3 or lowernSpeak with animals";
 

Вот как я их сейчас печатаю

     for (int i = 0; i < 2; i  )
    {
        cout << "n" << StoredItems[i].name << "n" << StoredItems[i].type << ", " << StoredItems[i].rarity;
        if (StoredItems[i].attunement == true)
        {
            cout << ", Requires Attunement.";
        }
        cout << "n" << StoredItems[MagicalItems[i]].description << "n";
    }
 

Большое спасибо!

Комментарии:

1. Вы не хотите присваивать эти значения от руки? Или вы не хотите печатать их с помощью цикла for? Объясните, что вы хотите уменьшить, сгущать непонятно для чего вы (не)хотите.

Ответ №1:

Лучший «объектно-ориентированный» способ сделать это-использовать реальный класс, а не класс данных:

 class RPGItem
{
 public:
   string name, type, rarity, description;
   bool attunement = true;

   RPGItem() {
   }

   RPGItem(string name, string type, string rarity, bool attunement, string description) {
       this->name = name;
       this->type = type;
       this->rarity = rarity;
       this->description = description;
       this->attunement = attunement;
   }
};

int main() 
{
    StoredItems[0] = RPGItem("Longsword  1", "Weapon",
                             "Unncommon", false,
                             "You have a  1 bonus to attack and damage rolls made with this magic weapon.");
    

    StoredItems[1] = RPGItem("Amulet of Health",
                             "Wondrous Item",
                             "Rare",
                             true,
                             "Your Constitution score is 19 while you wear this amulet. It has no effect on you if your Constitution is already 19 or higher without it.");
...
 

Теперь другой вариант-вместо этого сохранить данные в файле данных в файле YAML, JSON, CSV или чем-то еще и прочитать их с помощью анализатора.

Ответ №2:

Вместо этого вы можете инициализировать свой массив следующим образом :

 RPGItem StoredItems[5] = {

    {"Longsword  1",
    "Weapon",
    "Unncommon",
    "You have a  1 bonus to attack and damage rolls made with this magic weapon.",
    false},

    {"Amulet of Health",
    "Wondrous Item",
    "Rare",
    "Your Constitution score is 19 while you wear this amulet. It has no effect on you if your Constitution is already 19 or higher without it.",
     true},

    {"Dust of Dryness",
    "Wonderous Item",
    "Uncommon",
    "This small packet contains 1d6   4 pinches of dust. You can use an action to sprinkle a pinch of it over water. The dust turns a cube of water 15 feet on a side into one marble-sized pellet, which floats or rests near where the dust was sprinkled. The pellet's weight is negligible. Someone can use an action to smash the pellet against a hard surface, causing the pellet to shatterand release the water the dust absorbed. Doing so ends that pellet's magic. An elemental composed mostly of water that is exposed to a pinch of the dust must make a DC 13 Constitution saving throw, taking 10d6 necrotic damage on a failed save, or half as much damage on a successful one.",
    false},

    {"Nine Lives Stealer",
    "Weapon (any sword)",
    "Very Rare",
    "You gain a  2 bonus to attack and damage rolls made with this magic weapon. The sword has 1d8   1 charges. If you score a critical hit against a creature that has fewer than 100 hit points, it must succeed on a DC 15 Constitution saving throw or be slain instantly as the sword tears its life force from its body(a construct or an undead is immune). The sword loses 1 charge if the creature is slain. When the sword has no charges remaining, it loses this property.",
    true},

    {"Ring of Animal Influence";
    "Ring";
    "Rare";
    "This ring has 3 charges, and it regains 1d3 expended charges daily at dawn. While wearing the ring, you can use an action to expend 1 of its charges to cast one of the following spells:nAnimal friendship(save DC 13)nFear(save DC 13), targeting only beasts that have an Intelligence of 3 or lowernSpeak with animals",
    false}
};
 

И очистите свой цикл печати вот так:

 ostreamamp; operator<<(ostream amp;out, const RPGItem amp;item)
{
    out << "n" << item.name << "n" << item.type << ", " << item.rarity;
    if (item.attunement)
    {
        out << ", Requires Attunement.";
    }
    out << "n" << item.description << "n";
    return out;
}

for (int i = 0; i < 2;   i)
{
    cout << StoredItems[i];
}
 

Комментарии:

1. Можете ли вы объяснить, что следует изменить, когда в RPGItem добавляется новый участник?