我正在创建一个没有C++命令提示符的游戏。
这个游戏叫做PIG。你正在与电脑比赛,你的目标是通过掷骰子达到100游戏分数。如果你掷1分,你的回合结束,你的分数不会增加任何东西。如果你掷了任何其他数字,它会被添加到你的"转弯分数"中。滚动后,您可以选择再次滚动或"保持"。Holding将你的"回合得分"添加到你的"游戏得分"中,并将回合传给下一个玩家。
一切都按照我想要的方式进行,但现在我正在尝试创建一个playagain()函数,该函数将在游戏结束时询问用户是否希望再次玩。如果他们这样做了,应用程序就会重新启动,所有变量都为零。如果没有,程序将退出。
以下是我的问题:
if(comp_score == 100){
char ans;
cout << "Your opponent has reached a score of 100 and has won! Would you like to play again? [y/n] ";
cin >> ans;
if(ans == 'y'){
/*restarts application and zero's all variables*/
playagain();
} else if(ans == 'n'){ exit(); }}
if(play_score == 100){
char ans;
cout << "You have reached a score of 100 and have won! Would you like to play again? [y/n] ";
cin >> ans;
if(ans == 'y'){
/*restarts application and zero's all variables*/
playagain();
} else if(ans == 'n'){ exit(); }
}
TIA!
IMO实现这一点的最简单方法是使用while
循环:
bool keep_playing = TRUE;
while (keep_playing)
{
keep_playing = FALSE;
/* zero out variables */
/* rest of code to play the game */
if(comp_score == 100){
char ans;
cout << "Your opponent has reached a score of 100 and has won! Would you like to play again? [y/n] ";
cin >> ans;
if(ans == 'y'){
keep_playing = TRUE;
} else if(ans == 'n')
{ keep_playing = FALSE; }}
if(play_score == 100){
char ans;
cout << "You have reached a score of 100 and have won! Would you like to play again? [y/n] ";
cin >> ans;
if(ans == 'y'){
keep_playing = TRUE;
} else if(ans == 'n')
{ keep_playing = FALSE; }}
} -- while (keep_playing)...
分享并享受。
如果您使用Windows,请记住。您可以使用ShellExecute
打开一个新的游戏窗口,并给出一个返回代码0来关闭旧的窗口。就像这样。
#include <windows.h> // >>>>>> JACOBTECH EDIT.
if(comp_score == 100){
char ans;
cout << "Your opponent has reached a score of 100 and has won! Would you like to play again? [y/n] ";
cin >> ans;
if(ans == 'y'){
/*restarts application and zero's all variables*/
playagain();
} else if(ans == 'n'){ exit(); }}
if(play_score == 100){
char ans;
cout << "You have reached a score of 100 and have won! Would you like to play again? [y/n] ";
cin >> ans;
if(ans == 'y'){
ShellExecuteA(NULL, "open", "C:/GameDirectory/Game.exe", NULL, NULL, SW_NORMAL); //>>>>>> JACOBTECH EDIT.
return 0; //>>>>>> JACOBTECH EDIT.
} else if(ans == 'n'){ exit(); }
干杯!