我已经制作了Rock,paper,剪刀C ++程序,但是我很难尝试让它循环。在该计划中,它计算赢利和损失(关系不计算),当它结合时,它会一直持续到赢/输。当出现输赢时,任何变量(玩家获胜的pWins或玩家输入的pLosses)都会递增。它询问用户是否想再次播放,如果用户拒绝,则该节目结束并显示分数。
我的问题是如何在关系和用户选择继续游戏的情况下让程序循环。我知道我应该做些什么,但我不确定如何写它们。
if( pInput == ROCK && cInput == ROCK )
{
std::cout << "You tied with me!" << std::endl;
}
else if( pInput == ROCK && cInput == SCISSORS )
{
std::cout << "Drats! You win!" << std::endl;
}
else if( pInput == ROCK && cInput == PAPER )
{
std::cout << "Hah! Here comes the Hug of Death!" << std::endl;
}
else if( pInput == SCISSORS && cInput == SCISSORS )
{
std::cout << "Looks like we tied!" << std::endl;
}
else if( pInput == SCISSORS && cInput == ROCK )
{
std::cout << "Hah! I smashed you, so I win!" << std::endl;
}
else if( pInput == SCISSORS && cInput == PAPER )
{
std::cout << "Drats! You win!" << std::endl;
}
else if( pInput == PAPER && cInput == PAPER )
{
std::cout << "Drats! We tied!" << std::endl;
}
else if( pInput == PAPER && cInput == SCISSORS )
{
std::cout << "Hah! I win, because I'm a scissor!" << std::endl;
}
else if( pInput == PAPER && cInput == ROCK )
{
std::cout << "Drats! You gave me the Hug of Death!" << std::endl;
}
std::cout << "You won " << pWins << " times, and lost " << pLosses << "times.";
}
答案 0 :(得分:2)
仅供参考,您可以使用while
,for
和do-while
进行循环迭代。
你必须确定&#34;退出&#34;循环的标准。
以下是一个例子:
bool can_continue = true;
while (can_continue)
{
cout << "Do you want to continue?";
std::string answer;
getline(cin, answer);
if (answer = "no")
{
can_continue = false;
}
}
编辑1:
您可以通过检查关系简化程序:
if (pInput == cInput)
{
std::cout << "You tied with me!" << std::endl;
}
else
{
// Check for winning combinations.
}
答案 1 :(得分:1)
你正好考虑使用do while循环。你可以尝试这样的事情:
do {
//your program
} while(condition);
这样你的程序就可以运行一次,然后如果条件仍然如此,则继续运行。在你的情况下,条件是某种形式的博弈游戏。
答案 2 :(得分:0)
这可能是一般结构:
int main() {
do {
pInput = getPlayerInput();
cInput = getComputerInput();
result = checkResult(pInput, cInput); // here you could put your code, and you
// could also set pWins and pLosses here
if (result == tie) {
playAgain = true;
} else {
playAgain = askPlayAgain();
}
} while (playAgain);
print_results();
}