所以我在其他语言方面有相当多的经验,但我对c ++很新。我正在尝试创建一个简单的基于文本的RPG,其中所有的都是玩家和随机数量的敌人。所以问题是,当我试图在其中移动时,我从未遇到过敌人,所以我要么在创建真正的敌人对象时遇到问题,要么我的代码用于检查玩家是否与敌人在同一个位置工作,或者也许是别的。我真的很感激,一些帮助。感谢。
对不起,我的格式有点搞砸了。
#include <iostream>
#include <random>
#include <string>
using namespace std;
#define UP 1
#define RIGHT
class Character
{
public:
int health, armour, speed, x, y, attackPower;
Character()
{
health = 100;
armour = 100;
speed = 1;
}
bool isTouching(Character character)
{
if (x == character.x && y == character.y)
{
return true;
}
else
{
return false;
}
}
void move(string dir)
{
if (dir == "up")
{
y += speed;
}
else if (dir == "down")
{
y -= speed;
}
else if (dir == "right")
{
x += speed;
}
else if (dir == "left")
{
x -= speed;
}
}
void takeDamage(int damage)
{
if (armour > damage)
{
armour -= damage;
}
else
{
if (armour > 0)
{
int remainingDamage = damage - armour;
armour = 0;
health -= remainingDamage;
}
}
health -= damage;
}
void attack(Character* character)
{
character->takeDamage(attackPower);
}
};
class Player: public Character
{
public:
Player()
{
health = 100;
armour = 100;
speed = 1;
x = 10;
y = 10;
attackPower = 50;
}
};
class Enemy : public Character
{
public:
Enemy()
{
health = 100;
armour = 0;
speed = 1;
x = rand() % 100;
y = rand() % 100;
attackPower = 20;
}
};
int main()
{
Character player;
Enemy *enemies;
int numEnemies = rand() % 30 + 20;
enemies = new Enemy[numEnemies];
while (true)
{
string input;
cout << "Enter command: ";
cin >> input;
if (input == "exit" || input == "quit")
{
break;
}
if (input == "move")
{
string direction;
cout << "pick a direction: ";
cin >> direction;
player.move(direction);
for (int i = 0; i < sizeof(enemies) / sizeof(int); i++)
{
if (player.isTouching(enemies[i]))
{
cout << "You ran into an enemy!" << endl;
cout << "What would you like to do?: ";
string interactionInput;
cin >> interactionInput;
if (interactionInput == "attack")
{
player.attack(&enemies[i]);
enemies[i].attack(&player);
cout << "Enemy now at " << enemies[i].armour << " armour and " << enemies[i].health << " health" << endl;
cout << "You are now at " << player.armour << " armour and " << player.health << " health" << endl;
}
}
}
}
}
system("pause");
return 0;
}
答案 0 :(得分:3)
sizeof(enemies)
等于4或8,具体取决于虚拟内存地址空间的大小。
sizeof(int)
等于2或4,具体取决于您的编译器定义(基于底层硬件)。
所以sizeof(enemies) / sizeof(int)
介于1和4之间。
话虽如此,您只需使用numEnemies
代替。
如果您静态分配了enemies
数组(Enemy enemies[...]
),那么您可以使用:
sizeof(enemies)/sizeof(Enemy)
sizeof(enemies)/sizeof(*enemies)
sizeof(enemies)/sizeof(enemies[0]) // or any other index
但是由于你是动态分配它,它被视为一个指针(大小为4或8字节)。
答案 1 :(得分:0)
除了barak manos的回答中提到的问题之外,这条线可能是疏忽。
Character player;
我认为您打算使用:
Player player;
如果您使用第一行,则不会初始化x
和y
值。你会得到不可预知的行为。