つまり、基本的には、さまざまな種類のクリーチャーが登場する RPG ゲームのようなプログラムを作成する必要があります。各クリーチャーは Creature クラスのオブジェクトであり、ヒットポイント、強さなどのメンバー変数を持っています。
私が問題を抱えているのは、クラス間でダメージを処理および処理する関数を作成することです。
#include <iostream>
#include <string>
#include <stdlib.h>
using std::cout;
using std::cin;
using std::endl;
using std::string;
//Creature Base Class (Type 0)
class Creature
{
public:
Creature(int, int, int);
int gettype() {return type;}
int getstrength(){return strength;}
int gethitpoints() {return hitpoints;}
void sethitpoints(int);
string getspecies();
void printstats();
void dealdamage(Creature, Creature);
void takedamage(int);
private:
int type;
int strength;
int hitpoints;
};
Creature::Creature(int t, int s, int hp)
{
type = t;
strength = s;
hitpoints = hp;
}
void Creature::printstats()
{
cout << "This creature has: " << endl;
cout << strength << " strength" << endl;
cout << hitpoints << " hitpoints" << endl;
cout << "and is of type " << type << "(" << getspecies() << ")" << endl;
}
void Creature::sethitpoints(int a)
{
hitpoints = a;
}
string Creature::getspecies()
{
switch(type)
{
case 0: return "Creature";
case 1: return "Human";
case 2: return "Elf";
case 3: return "Demon";
case 4: return "Balrog";
case 5: return "Cyberdemon";
}
}
void Creature::dealdamage(Creature dealer, Creature target)
{
srand(5);
int damage;
damage = rand() % strength+1;
cout << dealer.getspecies() << " inflicts " << damage;
cout << " damage to " << target.getspecies() << "!" << endl;
target.takedamage(damage);
}
void Creature::takedamage(int damage)
{
sethitpoints((gethitpoints()-damage));
}
int main()
{
Creature monster1(0, 10, 100);
Creature monster2(1, 7, 90);
monster1.printstats();
monster2.printstats();
monster1.dealdamage(monster1, monster2);
monster2.printstats();
return 0;
}
現在、プログラムが私に与える出力は次のとおりです。
This creature has:
10 strength
100 hitpoints
and is of type 0(Creature)
This creature has:
7 strength
90 hitpoints
and is of type 1(Human)
Creature inflicts 5 damage to human!
This creature has:
7 strength
90 hitpoints
and is of type 1(Human)
したがって、dealdamage() 関数は機能しているように見えますが、takedamage() 関数は、ダメージを受けているクリーチャーのヒットポイントを適切に変更していません。
どんな助けでも大歓迎です。