所以基本上,我必须编写一个类似于 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() 函数并没有正确地改变受到伤害的生物的生命值。
任何帮助,将不胜感激。