我遇到了我怀疑是循环的麻烦。我正在建立一个简单的游戏,我认为我的两个while循环以某种方式干扰彼此。这是主要功能!在此先感谢!:
int main( int argc, char* argv[])
{
SDL_Startup();
while(Playing == false && quit == false)
{
StartingScreen.input();
StartingScreen.render();
character.input();
SDL_Flip( screen );
SDL_Delay(1000/FPS);
}
while(Playing == true && quit == false)
{
CAMERAGUY.Camera();
character.input();
character.adjust();
SuperSnail.move();
SuperSnail.attack();
TheWall.boundaries();
TheWall.render();
SuperSnail.render();
character.render();
character.reset();
HUD.render();
SDL_Flip(screen);
SDL_Delay(1000/FPS);
cout << StartingScreen.x << endl;
}
if(Playing == false)
cout << "Playing == false" << endl;
if(quit == true)
return 0;
}
所以bool play开始时设置为false,当我的角色用完生命时设置为true。因此,当在第二个循环中将播放设置为false时,它不会重复第一个循环。我只是想,如果我把两个循环放在一个单独的循环中,我想也许它会起作用。
答案 0 :(得分:1)
我已经用注释编辑了你的代码来解释它正在做什么(以及为什么它没有像你期望的那样表现):
int main( int argc, char* argv[])
{
SDL_Startup();
// Set `Playing` to false
while(Playing == false && quit == false)
{
// Do stuff which applies when `Playing` is false
//
// At some point, set `Playing` to true, so that
// the loop ends
}
while(Playing == true && quit == false)
{
// Now do stuff which applies when `Playing` is true
//
// At some point, set `Playing` to false, so that
// the loop ends
}
// Both loops have come to an end, and there
// is no code to return to the first loop
// so execution continues below:
// This line always executes because `Playing` is always false
// by this point:
if(Playing == false)
cout << "Playing == false" << endl;
// This conditional statement doesn't do what you think, because
// in the case that `quit == false`, the end of your `main` function
// is reached and returns 0 by default, meaning that the outcome
// is the same no matter what the value of `quit`
if(quit == true)
return 0;
}
解决方案:将两个循环包含在while(quit == false)
循环中。这意味着当第二个循环完成时,将再次评估第一个循环,直到您准备通过将quit
设置为true来停止执行。
其他一些提示:
表达quit == false
的更简洁方式是!quit
。
表达Playing == true
的更简洁方式是Playing
。
以almost certainly a bad idea的方式使用全局变量,您应该重新考虑您的设计。
答案 1 :(得分:0)
这很简单。在你当前的实现中,如果第二个循环结束,你将永远不会返回到你的第一个while循环,因为你到达了主程序的return
。
我猜你应该总是只为游戏使用一个主循环。