fork download
  1. #include <iostream>
  2. #include <ctime>
  3. #include <string>
  4. using namespace std;
  5.  
  6. bool valid_hand(int hand)
  7. {
  8. return 1 <= hand && hand <= 3;
  9. }
  10. std::string hand_to_str(int hand)
  11. {
  12. switch (hand)
  13. {
  14. case 1: return "Rock";
  15. case 2: return "Scissors";
  16. case 3: return "Cloth";
  17. default: return "(invalid)";
  18. }
  19. }
  20.  
  21. void print_hand(int hand, int npc)
  22. {
  23. cout << "Your hand: " << hand_to_str(hand) << endl;
  24. cout << "NPC's hand: " << hand_to_str(npc) << endl;
  25. }
  26.  
  27. int judge(int hand, int npc)
  28. {
  29. --hand;
  30. --npc;
  31. return (3 + hand - npc) % 3;
  32. }
  33.  
  34. void show_score(int urscore, int npcscore)
  35. {
  36. cout << "Now your score is: " << urscore << endl;
  37. cout << " npc's score is: " << npcscore << endl;
  38. }
  39.  
  40. void wait_key(int& end)
  41. {
  42. cout << "\n - Press any key to continue the game." << endl;
  43. cin >> end;
  44. }
  45.  
  46. int main(void)
  47. {
  48. int urscore = 0;
  49. int npcscore = 0;
  50. int end = 0;
  51.  
  52. while (!end) {
  53. int hand;
  54. int npc = rand() % 3 + 1;
  55.  
  56. do
  57. {
  58. cout << "Select => 1:Rock | 2:Scissors | 3:Cloth" << endl;
  59. cin >> hand;
  60. } while (!valid_hand(hand));
  61.  
  62. print_hand(hand, npc);
  63. int j = judge(hand, npc);
  64. if (j == 0) {
  65. cout << "Result : Draw" << endl;
  66. ++urscore;
  67. ++npcscore;
  68. }
  69. else if (j == 1) {
  70. cout << "Result : Lose" << endl;
  71. ++npcscore;
  72. }
  73. else if (j == 2) {
  74. cout << "Result : Win" << endl;
  75. ++urscore;
  76. }
  77. show_score(urscore, npcscore);
  78. wait_key(end);
  79. }
  80. return 0;
  81. }
Success #stdin #stdout 0s 4520KB
stdin
1
0
2
0
3
0
4
3
1
stdout
Select => 1:Rock | 2:Scissors | 3:Cloth
Your hand: Rock
NPC's hand: Scissors
Result : Win
Now your score is: 1
    npc's score is: 0

 - Press any key to continue the game.
Select => 1:Rock | 2:Scissors | 3:Cloth
Your hand: Scissors
NPC's hand: Scissors
Result : Draw
Now your score is: 2
    npc's score is: 1

 - Press any key to continue the game.
Select => 1:Rock | 2:Scissors | 3:Cloth
Your hand: Cloth
NPC's hand: Rock
Result : Win
Now your score is: 3
    npc's score is: 1

 - Press any key to continue the game.
Select => 1:Rock | 2:Scissors | 3:Cloth
Select => 1:Rock | 2:Scissors | 3:Cloth
Your hand: Cloth
NPC's hand: Scissors
Result : Lose
Now your score is: 3
    npc's score is: 2

 - Press any key to continue the game.