A very simple solution: create a separate function, e.g., attackMonster(monsterClass& monster). Then, instead of case 1: attack pig; case 2: attack blob...
void attackMonster(monsterClass& monster)
{
monster.setMonster(...); // or just use the monster's default values, perhaps set in the constructor
// .. all the same code. Instead of hard-coding the names, use monter.getName() or similar
}
Then:
attackMonster(pig);
attackMonster(some-other-instantiated-monster);
So I should be creating an attackMonster class and make a function that I can call in main like attackMonster(pig) and it would attack the pig?
No, attackMonster is a function, not a class. Different concepts.
About the idea of using an array of monsters, first I have to understand what your code is doing. You have a notion of what a pig is, which is something with 5 hit points, 5 for stamina, an amount of gold between 1 and 5 and a random damage between 0 and 0 (???). If that's the case, I would create a class MonsterType which contains those parameters that can be used to create a specific pig. Then you can have an array of MonsterType objects, which I would call `bestiary'.
int random_in_range(int min, int max) {
return min + std::rand() % (max - min + 1);
}
class MonsterType {
std::string name;
int hitpoints;
int experience;
int min_gold;
int max_gold;
int min_damage;
int max_damage;
MonsterType(std::string name, int hitpoints, int experience, int min_gold, int max_gold, int min_damage, int max_damage)
: name(name),
hitpoints(hitpoints),
experience(experience),
min_gold(min_gold),
max_gold(max_gold),
min_damage(min_damage),
max_damage(max_damage) {
}
Monster create_instance() const {
return Monster(name,
hitpoints,
experience,
random_in_range(min_gold, max_gold),
random_in_range(min_damage, max_damage));
}
};
// [...] somewhere in Main.cpp
MonsterType const bestiary[4] = {
MonsterType("Pig", 5, 5, 1, 5, 0, 0),
MonsterType("Blob", 7, 5, 4, 15, 0, 1),
MonsterType("Goat", 10, 7, 4, 18, 0, 2),
MonsterType("Sheep", 20, 22, 7, 26, 0, 3)
};
// [...]
int random_bestiary_index = std::rand() % 4;
Monster monster = bestiary[random_bestiary_index].create_instance();
while (monster.isAlive() && player.isAlive()) {
// Here goes your single copy of the loop
// [...]
}