这段代码有什么问题?它会检测我是否已经到达怪物的坐标但是只有其中一个,或者至少是最近的一个。如果我去其他坐标,它并没有告诉我怪物已经出现。不知道为什么,因为每次输入“北方”时我都会循环浏览怪物矢量。 这是代码。
怪物类:
class Monster
{
public:
std::vector<std::string> names;
std::vector<double> posx; // North - South
std::vector<double> posy; // East - West
bool compareCoords(double monsterPosX, double monsterPosY);
void cMonster(std::string monsterName, double monsterPosX, double monsterPosY);
void randomSpawn();
protected:
private:
};
compareCoords检测那些坐标上是否存在怪物以及cMonster(创建怪物)功能:
void Monster::cMonster(std::string monsterName, double monsterPosX, double monsterPosY)
{
if (compareCoords(monsterPosX, monsterPosY) == false)
{
names.push_back(monsterName);
posx.push_back(monsterPosX);
posy.push_back(monsterPosY);
std::cout << "Monster " << monsterName << " has been created at X: " << monsterPosX << " Y: " << monsterPosY << std::endl;
}
}
bool Monster::compareCoords(double monsterPosX, double monsterPosY)
{
for (unsigned int i = 0; i < posx.size(); i++)
{
if (monsterPosX == posx[i] && monsterPosY == posy[i])
{
return true;
}
}
return false;
}
主:
int main()
{
srand(time(0));
Monster newenemy;
Character newplayer;
newenemy.cMonster("Weezo", 1, 0);
newenemy.cMonster("Weezo", 2, 0);
newplayer.posx.push_back(0);
newplayer.posy.push_back(0);
home:
std::cout << "-->> ";
std::string userInput;
std::cin.clear();
getline(std::cin, userInput);
if (!userInput.compare("north"))
{
newplayer.headNorth();
for (unsigned int i = 0; i < newenemy.names.size(); i++)
{
if (newplayer.posx[i] == newenemy.posx[i] && newplayer.posy[i] == newenemy.posy[i])
{
std::cout << "A " << newenemy.names[i] << " has appeared." << std::endl;
}
}
}
else if (!userInput.compare("south"))
{
newplayer.headSouth();
for (unsigned int i = 0; i < newenemy.posx.size(); i++)
{
if (newplayer.posx[i] == newenemy.posx[i] && newplayer.posy[i] == newenemy.posy[i])
{
std::cout << "A " << newenemy.names[i] << " has appeared." << std::endl;
}
}
}
else
{
std::cout << "You have entered an invalid command." << std::endl;
}
}
^正如你在这里看到的那样,它显示的是我在大猩猩坐标时的情况,而不是第二个怪物唐纳德特朗普。它只是忽略了第二个。
我被困在这里几个小时,我不明白可能出现的问题。谢谢!