C ++中的岩纸剪刀

问题描述 投票:-2回答:2

我正在尝试使用C ++练习10第4章编写“原理与练习”一书。练习即将编写一个Rock Paper Scissor游戏,不使用随机函数让计算机在岩石,纸张或剪刀之间“选择” ,所以你必须找到一种让计算机随机选择的方法。顺便说一句,重点是我的程序跟踪玩家和计算机得分。现在的问题是我不知道如何分配分数。我想出了这个:

enum types {ROCK, PAPER, SCISSORS}
.
.
.
.
.
/* this is the part where i check the score */

 // all cases the player would lose
if (player == ROCK && computer == PAPER)    // paper beats rock
    ++computer_score;
else if (player == PAPER && computer == SCISSORS)   // scissors beat paper
    ++computer_score;
else if (player == SCISSORS && computer == ROCK)    // rock beats scissors
    ++computer_score;

else // all other cases the player would win
    ++player_score;

问题是我不认为这段代码是好的。有更聪明的方法吗?

在互联网上,我找到了由数学家Nick Maclaren制作的版本。这是他的代码:

vector<string> words;
words.push_back("Rock");
words.push_back("Paper");
words.push_back("Scissors");

string guess;
cout << "Make a guess - Rock, Paper or Scissors\n";
while (cin >> guess) {
    int yours, mine; //-your- is the user choice. -mine- is the computer choice
    if (guess == "Rock")
        yours = 0;
    else if (guess  == "Paper")
        yours = 1;
    else if (guess  == "Scissors")
        yours = 2;
    else {
        cout << "Invalid guess - Rock used\n";
        yours = 0;
    }
    seed = (13*seed)%256;
    mine = seed%3;
    if (mine == yours) // draw
        cout << "Both guesses were " << words[yours] << " - no winner\n";
    else if ((3+mine-yours)%3 == 1) // computer wins
        cout << words[mine] << " beats " << words[yours] << " - I win\n";
    else // player wins
        cout << words[yours] << " beats " << words[mine] << " - you win\n";
}     

顺便说一下,here是他制作完整代码的链接。如果你查看整个代码,也许你会理解更多。

所以他使用另一种方法,但我不理解他的代码的这一部分:

else if ((3+mine-yours)%3 == 1)//<-- I don't understand this conditional expression
    cout << words[mine] << " beats " << words[yours] <<
        " - I win\n";

我得到的是,如果该表达式的结果为1,则计算机获胜,否则获胜者是玩家,但我不理解逻辑。

c++
2个回答
1
投票

你要看的是我的你的mod 3,如果我的你的= = 1 mod 3然后我的胜利,如果你不相信看三个案例。

(3+mine-yours)%3

这看起来差异mod 3,+ 3是为了确保3 +我的你的积极在被%评估之前

如果你不确定%https://www.cprogramming.com/tutorial/modulus.html

或什么模型是https://en.wikipedia.org/wiki/Modular_arithmetic


0
投票

这段代码让我想起为什么聪明才是善的敌人。

我建议你看看这里发布的类似问题的答案:Rock, Paper, Scissors Game Java

基本上,最好为选择提供抽象类的接口,为不同的有效选择提供实现,并让类决定它是否从其他实现中获胜。

© www.soinside.com 2019 - 2024. All rights reserved.