我想用C ++编写一个小游戏。
我想写一个方法" attack"设置攻击后的图形状态。 玩家和敌人有两个例子。该课程如下:
class figure {
private:
string name;
int hp;
int strength;
int defense;
public:
void attack(int xstrength) {
// This method gets the Input values of the player and should calculate
// and set the new hp stats of the enemy after an attack, sort of
hp = hp - (xstrength - defense);
}
};
但我怎么称这种方法?我是否需要编程一个只能得到的单独方法 实例的强度值?,因为我不能用这种方式调用实例:
enemy.attack();
因为我需要输入实例播放器的强度。 或者我只能访问像
这样的实例的一个值enemy.attack(player->get_xstrength)
使用方法:
void get_strength() {
return stength
};
如果我用更多的值来扩展类图,例如阻力,等级,状态等。我必须 编程很多get和设置方法。
答案 0 :(得分:0)
您的方法应该是:
void attack(figure & target) {
target.hp -= strength - target.defense;
}
通过这种方式,您可以指定数字攻击的目标,并且可以让您访问受攻击的数字属性。然后你可以:
figure player, enemy;
enemy.attack(player);
另请注意,您必须使用某种方法来设置这些属性,这些属性是私有的,而不是在构造函数中设置,因此在类中,因为它现在无法设置这些值,这意味着它们将是垃圾内存表示,或者最好是 - 零,具体取决于编译器的实现。
最后但并非最不重要的一点是,您可能还想在目标hp计算后进行检查以查看该数字是否仍然存在,即if (target.hp <= 0) ... // "target" is dead