如何在c ++中执行一次无限循环执行一次

时间:2012-12-28 19:01:13

标签: c++ loops

我正在用c ++创建游戏。我目前的目标是在永久循环中检查玩家的健康状况,以检查他是否已经死亡。虽然他是,我想要它cout<<你死了。但是因为cout<<是 在while语句中,一直检查健康状况,结果输出并执行cout<< 多次。我想让它在一个循环中永远检查健康状况,如果健康状况是< 1,我想要它cout<< “你死了”;只有一次。有没有办法告诉while语句只执行一次?继承了我目前的声明:

bool gamerunning = true;

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

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

7 个答案:

答案 0 :(得分: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;
  }
}

答案 1 :(得分:2)

为什么不这样?

bool gamerunning = true;

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

如果你想保留你的循环,你可以添加额外的bool变量 - userDead,只在userDead为false时才进行检查,在写完输出后你可以将它设置为true。

答案 2 :(得分: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;
    }
}

答案 3 :(得分:1)

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

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;
        }
    }
}

答案 4 :(得分: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";
   }
}

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

答案 5 :(得分: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;
    }
}

答案 6 :(得分: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;
       }
    }
}