我正在努力完成一本练习 Programming Principles and Practice using 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,那么计算机就会获胜,否则获胜者就是玩家,但我不理解逻辑。
答案 0 :(得分:1)
你想要看的是我的你的mod 3,如果我的你的= = 1 mod 3然后我的胜利,如果你不相信看三个案例。
(3+mine-yours)%3
这看着差异mod 3,+ 3是为了确保3 +你的矿井在被%
评估之前是积极的答案 1 :(得分:0)
这段代码让我想起为什么聪明才是善的敌人。
我建议您查看此处发布的类似问题的答案:Rock, Paper, Scissors Game Java
基本上,为选择提供抽象类接口,为不同的有效选择提供实现,并让类决定是否从其他实现中获胜是很好的。