繁体   English   中英

如何制作C ++程序循环的一部分?

[英]How do I make parts of a C++ program loop?

我制作了一个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.";

}

仅供参考,您可以使用whilefordo-while进行循环迭代。

您将必须确定循环的“退出”条件。

这是一个例子:

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

您正在考虑使用do while循环。 您可以尝试这样的事情:

do {
    //your program
} while(condition);

这样,您的程序将运行一次,然后在您的条件仍然成立时继续运行。 您的情况是布尔型的某种形式的游戏。

这可能是一般结构:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM