我的C ++代码遇到了困难。我是初学者。就像,只有非常基本的C ++知识。所以,我真的无法想办法做到这一点。我想过使用C ++命令制作一个RPG游戏,接近完成它。但不知何故,我无法为英雄保持健康。看一下代码,
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class player
{ public:
int health = 100;
};
int battle();
void death();
int main()
{
int abc;
player hero;
hero.health = abc;
int a;
int replay = 1;
cout << "You have 100 Hp. \n";
while (replay == 1)
{
srand(time(0));
cout << "\n Press 1 to move forward; 2 To stay. \n";
cin >> a;
if (a == 2)
{
if (rand() % 4 + 1 != 1)
{
cout << "You stay at your place. \n";
}
else
{
cout << "Enemy Attacks! (20 Hp) \n";
//battle(hero.health);
//cout << "\n Press 1 to continue. \n";
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else if (a == 1)
{
if (rand() % 2 + 1 != 1)
{
cout << "You moved forward. No one around. \n";
}
else
{
cout << "You move forward. Enemy attacks! (20 Hp) \n";
battle(abc);
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else
{
cout << "Sorry. Please enter a valid move. \n";
}
}
return 0;
}
int battle(int x)
{
player enemy;
enemy.health = 20;
player hero;
int y;
while (enemy.health >= 0)
{
int eattack = rand() % 15 + 7;
int attack = rand() % 10 + 1;
int escape = rand() % 4 + 1;
cout << "\n Press 1 to attack. 2 to flee \n";
cin >> y;
if (y == 2)
{
if (escape != 1)
{
cout << "Can't escape! \n";
cout << "Enemy attacked! Dealing a damage of: " << eattack << " Hp. \n";
hero.health = hero.health - eattack;
cout << "Your Hp is: " << hero.health;
}
else
{
goto Aftermath;
}
}
else if (y != 1)
{
cout << "Sorry. Please enter a valid response. \n";
}
else
{
cout << "You attack the enemy. \n";
cout << "You deal a damage of: " << attack;
enemy.health = enemy.health - attack;
if (enemy.health >= 0)
{
cout << "\n Enemy attacks you, dealing: " << eattack << " Hp damage.";
hero.health = hero.health - eattack;
cout << "\n You have: " << hero.health << " Hp left.";
}
}
if ((hero.health <= 0) || (hero.health == 0))
{
death();
enemy.health = -1;
}
}
if (hero.health > 0)
{
cout << "\n Enemy fainted!";
//cout << "You found Hp Potion! Your Hp was refilled.";
}
Aftermath:
if ((hero.health > 0) && (enemy.health > 0))
{
cout << "Escaped Successfully! \n";
}
return x;
}
void death()
{
cout << "You died!";
}
如你所见,我已经呼吁battle(abc)
和battle(hero.health)
[我现在评论过]但问题是,它说&#34;函数{{1}太多参数}。以前,我只是避免参数和创建对象&#34;英雄&#34;在战斗方法本身。但是每当你完成一个战斗序列时,它会再次返回并再次声明它,从而使其恢复健康状态。 [查看int battle()
]
我真的不了解全局变量等等。我只是想知道是否有解决方法或解决此参数问题的方法。任何其他建议,以健康作为一个常数&#39;并且每次都没有宣布也被热烈接受。非常感谢你!
P.S。缩短代码的建议也接受但请,我是初学者。所以先进的策略现在超出了我的技能。我需要时间来掌握概念。
答案 0 :(得分:2)
您在main
方法之前声明了该函数,然后在main
方法之后实现该函数。
问题是,您将函数实现为:
int battle(int x)
但这与您的声明不符:
int battle();
只需更改您的函数声明块,以便battle
函数与预期的签名匹配:
int battle(int x);
void death();
这将使您的代码编译,但您仍然需要执行一些步骤。
我会给你一个启动器:不是将生命值传递到battle
,而是传递整个玩家。
void battle(Player &player)
{
// ...
}
然后您可以直接在battle
功能中修改玩家的生命值。
然后你会用:
来调用它 battle(hero);