Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. using namespace std;
  5.  
  6. enum RPSChoice
  7. {
  8.     ROCK = 1,
  9.     PAPER = 2,
  10.     SCISSORS = 3
  11. };
  12.  
  13. // Convert an user input character to a choice ID
  14. int characterToChoice(char c)
  15. {
  16.     c = tolower(c);
  17.     if (c == 'r')
  18.         return ROCK;
  19.     else if (c == 's')
  20.         return SCISSORS;
  21.     else if (c == 'p')
  22.         return PAPER;
  23.     else
  24.         return 0; // Not a proper choice!
  25. }
  26.  
  27. // Decide who is the winner
  28. int winner(int user1, int user2) {
  29.     if (user1 == user2) {
  30.         return 0; // tie
  31.     }
  32.     else if ((user1 == ROCK && user2 == PAPER) ||
  33.              (user1 == PAPER && user2 == SCISSORS) ||
  34.              (user1 == SCISSORS && user2 == ROCK)) {
  35.         return 2; // user2 is the winner
  36.     }
  37.     else {
  38.         return 1; // user1 is the winner
  39.     }
  40. }
  41.  
  42. // Print someone's decision at the game
  43. void printDecision(string who, int choice) {
  44.     cout << who; // no matter what, we will tell who took a decision
  45.     if (choice == ROCK)
  46.         cout << " chose ROCK!" << endl;
  47.     else if (choice == PAPER)
  48.         cout << " chose PAPER!" << endl;
  49.     else if (choice == SCISSORS)
  50.         cout << " chose SCISSORS!" << endl;
  51. }
  52.  
  53. void playRPS (char x) {
  54.     int user1 = characterToChoice(x);
  55.     int user2 = rand() % 3 + 1;
  56.    
  57.     printDecision("You", user1);
  58.     printDecision("The computer", user2);
  59.    
  60.     int result = winner(user1, user2);
  61.     if (result == 0)
  62.         cout << "It's a TIE!" << endl;
  63.     else if (result == 1)
  64.         cout << "You WON!" << endl;
  65.     else
  66.         cout << "You LOSE!" << endl;
  67. }
  68.  
  69. int main() {
  70.     char letter;
  71.  
  72.     cout << "Welcome to COP3014 ROCK PAPER SCISSORS!\n\n";
  73.  
  74.     cout << "Please select: " << endl
  75.          << "Rock(r), Paper(p), or Scissors(s)? " << endl
  76.          << "Or enter q to quit --> ";
  77.  
  78.     bool correctInput = false;
  79.  
  80.     do {
  81.         cin >> letter;
  82.    
  83.         if (characterToChoice(letter) != 0) {
  84.             playRPS(letter);
  85.             correctInput = true;
  86.         }
  87.         else {
  88.             cout << "Please enter r, p, or s" << endl;
  89.         }
  90.     } while (!correctInput);
  91.  
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement