注意:这是家庭作业。
我正在尝试制作一个玩猪游戏的程序! Pig是一款符合以下规则的游戏:
1. First to get 100 GAME POINTS is the victor.
2. On your turn, you roll a dice. If you get a 1 at any roll, you end your turn and add 0 to your GAME SCORE.
3. If you roll any value other than a 1, you have the option to HOLD or PLAY. If you PLAY, your roll is added to your TURN SCORE and you roll again. If you HOLD, your TURN SCORE is added to your GAME SCORE and the turn passes to the computer.
游戏很容易出现,直到我遇到以下问题(见代码):
int player(){
char PlayAgain = 'Y';
int turn_score = 0;
while (PlayAgain != 'N' || PlayAgain != 'n'){
int dice;
srand(time(NULL));
dice = rand() % 6 + 1;
turn_score = turn_score + dice;
if (dice != 1){
cout << "You rolled a " << dice << "! Would you like to roll again? [Y/N]: ";
cin >> PlayAgain;
if (PlayAgain == 'N' || PlayAgain == 'n'){
/*END TURN AND return turn_score;*/
}
}
if (dice == 1){
cout << endl << "Oops! You rolled a 1! Your turn is ended, and you add nothing to your score.\n";
system("PAUSE");
/*END TURN, NO SCORE ADDED*/
}
}
}
如何让程序提前结束循环(如果播放HOLDS或dice == 1)并返回正确的值(如果HOLD,则返回turn_score。否则返回0)? [见两节有用]
答案 0 :(得分:1)
您可以使用break
退出循环。既然你说要返回“正确的价值”,那么你应该这样做:
在第一个if子句
上if (PlayAgain == 'N' || PlayAgain == 'n'){
/**Game-Specific logic here**/
return turn_score
}
并在第二个:
if (dice == 1){
cout << endl << "Oops! You rolled a 1! Your turn is ended, and you add nothing to your score.\n";
/**Game-Specific logic here**/
cin.get();
return turn_score;
}
return语句不需要在函数的末尾,并且多个return语句可以在同一个函数内共存
答案 1 :(得分:0)
而不是纠正你的代码我想让你明白这里实际需要什么。
听说过break;
声明。让我们通过一个简单的例子来理解
请参阅以下代码段,其中您的程序正在从用户那里获取输入,它会继续接收用户的输入,直到您按下“A&#39;
char var;
while(true)
{
cin>>var;
if(var=='A') break;
}
现在在这个程序中,while循环设置为true
并且将继续运行并从用户那里获取输入,if语句将不会运行,直到用户输入&#39; A&#39 ;。而那一刻&#39; A&#39;作为输入,break
会将控制权移出while
循环。
答案 2 :(得分:0)
如何在循环中使用'return'语句(具体取决于具体情况)?这将破坏循环和函数,但返回您需要的值。