我正在尝试创建一个非常简单的回合制文本 RPG 游戏。代码编译并运行,但攻击和修复功能似乎没有改变变量的值。我很确定这是与继承有关的问题,但我不确定。
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
struct Stats {
int hp;
int def;
int atk;
int skl;
};
class Character {
public:
Character();
virtual void getHit(int) = 0;
int attack(int);
void defend();
virtual int getHP() = 0;
protected:
Stats m_Stats;
};
Character::Character() {
m_Stats.hp = 0;
m_Stats.def = 0;
m_Stats.atk = 0;
m_Stats.skl = 0;
}
int Character::attack(int def)
{
return (m_Stats.atk - def);
}
class Player : public Character {
public:
Player();
void getHit(int);
void healSelf();
void fireBall();
int getAtk();
int getHP();
};
Player::Player()
{
m_Stats.hp = 100;
m_Stats.atk = 30;
m_Stats.def = 10;
m_Stats.skl = 10;
}
int Player::getHP()
{
return m_Stats.hp;
}
int Player::getAtk()
{ return m_Stats.atk; }
void Player::getHit(int atk)
{
m_Stats.atk += m_Stats.def - atk;
}
void Player::healSelf()
{
m_Stats.hp += m_Stats.skl;
if(m_Stats.hp > 100)
m_Stats.hp = 100;
}
class Enemy : public Character {
public:
Enemy();
void getHit(int);
void chooseAction();
void rage();
int choose();
void defend();
void resetAtk();
int getAtk();
int getHP();
};
Enemy::Enemy()
{
m_Stats.hp = 150;
m_Stats.atk = 40;
m_Stats.def = 5;
m_Stats.skl = 5;
}
int Enemy::getHP()
{
return m_Stats.hp;
}
int Enemy::getAtk()
{
return m_Stats.atk;
}
void Enemy::resetAtk()
{
m_Stats.atk = 40;
}
int Enemy::choose()
{
srand(time(0));
int c = rand() % 3;
if(c == 0)
cout << "Enemy chooses to attack!\n";
else if(c == 1)
cout << "Enemy is raging!\n";
else if(c == 2)
cout << "Enemy chooses to defend!\n";
return c;
}
void Enemy::rage()
{
m_Stats.atk += 3;
}
void Enemy::getHit(int atk)
{
m_Stats.atk += m_Stats.def - atk;
m_Stats.def = 5;
}
void Enemy::defend()
{
m_Stats.def += 2;
}
int main()
{
Player p;
Enemy e;
bool done = false; int choice, move;
cout << "The enemy faces you!\n";
while(!done)
{cout << "1) Attack 2) Heal Self. ";
cin >> choice;
if(choice == 1)
{ e.getHit(p.getAtk());}
else if(choice == 2)
{p.healSelf(); }
cout << "Your HP: " << p.getHP() << "\n";
cout << "Enemy HP: " << e.getHP() << "\n";
choice = e.choose();
if(choice == 1)
{p.getHit(e.getAtk());
e.resetAtk();
}
else if(choice == 2)
e.rage();
else if(choice == 3)
e.defend();
cout << "Your HP: " << p.getHP() << "\n";
cout << "Enemy HP: " << e.getHP() << "\n";
if(p.getHP() == 0 || e.getHP() == 0)
done = true;
}
if(p.getHP() > e.getHP())
cout << "You won!" << endl;
else
cout << "You lost!" << endl;
system("PAUSE");
return 0;
}
样本输出
敌人面对你! 1) 攻击 2) 治疗自我。1 你的生命值:100 敌人HP:150 敌人选择防守! 你的生命值:100 敌人HP:150 1) 攻击 2) 治疗自我:2 你的生命值:100 敌人HP:150
是的,输出并不漂亮,但我会在代码稳定后推迟清理输出。任何帮助,将不胜感激。谢谢。