Learn C++ - Rock, Paper, Scissors Solution

Here’s my solution for the exercise :slight_smile:

#include <iostream>
#include <stdlib.h>
int main() {

srand (time(NULL));

int computer = rand() % 3 + 1;

int user = 0;
  
  //Creating strings to avoid repetition
  std::string roc = "1) ✌️Rock\n";
  std::string pap = "2) ✋Paper\n";
  std::string sci = "3) ✌️Scissors\n";
  

std::cout << "====================\n";
std::cout << "rock paper scissors!\n";
std::cout << "====================\n";

std::cout << roc;
std::cout << pap;
std::cout << sci;

std::cout << "Choose: ";
std::cin >> user;

  
std::cout << "\nYou  choose ";
  
  //Displaying user choice
  switch(user){
    case 1 :
    	std::cout << roc;
    	break;
    case 2 :
    	std::cout << pap;
    	break;
    case 3 :
    	std::cout << sci;
    	break;
    default :
    	std::cout << "Invalid Option\n";
  }
  
  //Displaying computer choice
std::cout << "Comp choose ";
    switch(computer){
    case 1 :
    	std::cout << roc;
    	break;
    case 2 :
    	std::cout << pap;
    	break;
    case 3 :
    	std::cout << sci;
    	break;
    default :
    	std::cout << "Invalid Option\n";
  }
  
  
  //Win Lose Draw Logic
  if(user == computer){
    std::cout << "Draw Game\n";
  }
  else if(user == 1 && computer == 3){
    std::cout << "You Win\n";
  }
  else if(user == 3 && computer == 2){
    std::cout << "You Win\n";
  }
  else if(user == 2 && computer == 1){
    std::cout << "You Win\n";
  }
  else{
    std::cout << "Computer Wins!\n";
  }
  
}
2 Likes

Id imagine you could have a function for the switch statements and just pass in the user and computer variable which would allow in future for you to have multiple players.

1 Like

woohoo @cormaccallan great work!

feel free to upload this to the official Learn C++ GitHub repo: https://github.com/Codecademy/learn-cpp

:slight_smile:

Why are we doing this? I can’t understand, why first random number module 3 and then add 1?
rand() % 3 + 1

The computer will draw a random number. % will divide that number with the int of 3 as indicated. The result will be 0.xxx, 1.xxx or 2.xxx so, if you at 1 then the sum will be 1.xxx, 2.xxx or 3.xxx. Now since this value was indicated as a int, the computer will drop the .xxx under the 1, 2 or 3.

What I need help with is that i keep getting an error in my debugging that srand(time(NULL)) comes up with “time was not declared in this scope”. I am using stdlib.h … so WTH?

Here is my solution