2

我正在用 C++ 创建一个游戏。我目前的目标是在一个永远循环中检查玩家的健康状况,以检查他是否已经死亡。当他在的时候,我想让它知道<<你已经死了。但由于 cout << 在 while 语句中,一直在检查健康状况,结果输出并执行 cout << 多次。我希望它在循环中永远检查健康状况,如果健康状况 < 1,我希望它 cout << "You are dead"; 只有一次。有没有办法告诉 while 语句只执行一次?这是我当前的 while 语句:

bool gamerunning = true;

while (gamerunning == true) //While game is running...
{
if (health < 1) //If player is dead...
{
cout << "You are dead";
}
}

执行此代码会多次输出“你死了”。我希望它继续检查此循环中的运行状况,但我希望 cout 执行一次,因此它不会一遍又一遍地重复相同的消息。如果您能提供一个小例子来说明如何阻止这种情况,我们将不胜感激。非常感谢你们!

4

7 回答 7

2

听起来你想在玩家死亡时停止游戏运行,在这种情况下你想要这样:

while (gamerunning == true) //While game is running...
{
  if (health < 1) //If player is dead...
  {
    cout << "You are dead";
    gamerunning = false;
  }
}

如果没有,那么您可以保留另一个bool说明是否发生了死亡输出:

bool deadOutput = false;
while (gamerunning == true) //While game is running...
{
  if (health < 1 && !deadOutput) //If player is dead...
  {
    cout << "You are dead";
    deadOutput = true;
  }
}
于 2012-12-28T19:04:46.817 回答
2

为什么不这样呢?

bool gamerunning = true;

while (gamerunning == true) //While game is running...
{
   if (health < 1) break
}
cout << "You are dead";

如果你想保持你的循环,你可以添加额外的布尔变量 - userDead,只有当 userDead 为 false 时才进行检查,并且在写入输出后你可以将其设置为 true。

于 2012-12-28T19:06:18.453 回答
1

这个怎么样?

bool gamerunning = true;
bool output_done = false;

while (gamerunning == true) //While game is running...
{
    if ((health < 1) && (output_done != true)) //If player is dead...
    {
        cout << "You are dead";
        output_done = true;
    }
}
于 2012-12-28T19:04:40.880 回答
1

您可以使用 abool来跟踪它是否已经发生:

bool gamerunning = true;
bool printed = false;

while (gamerunning == true) //While game is running...
{
    if (health < 1) //If player is dead...
    {
        if (!printed) {
            cout << "You are dead";
            printed = true;
        }
    }
}
于 2012-12-28T19:05:52.687 回答
0
bool gamerunning = true;

while (gamerunning == true) //While game is running...
{
    if (health < 1) //If player is dead...
    {
         cout << "You are dead";
         break;
    }
}

或者

bool gamerunning = true;

while (gamerunning == true) //While game is running...
{
    if (health < 1) //If player is dead...
    {
         cout << "You are dead";
         gamerunning = false;
    }
}
于 2012-12-28T19:06:26.803 回答
0
bool gamerunning = true;
bool playerDead = false

while (gamerunning == true) //While game is running...
{
    if (health < 1) //If player is dead...
    {
       if (!playerDead) 
       {
           cout << "You are dead";
           playerDead = true;
       }
    }
}
于 2012-12-28T19:07:12.560 回答
0

通常你会有一个状态机..但一个简单的方法是跟踪..

bool gamerunning = true; bool alive = true;

while (gamerunning == true) //While game is running...
{
   if (health < 1 && alive) //If player is dead...
   {
      alive = false;
      cout << "You are dead";
   }
}

于 2012-12-28T19:04:43.397 回答