Rock-Paper-Scissors program in C++

Rock-Paper-Scissors program in C++

This program is a simple game where the player has to choose one of the options. The computer will generate a random number to choose it’s option. 1 = ‘rock’, 2 = ‘paper’ and 3 = ‘scissors’. You have to choose 4 when you want to exit the game.

Output:

Rock-Paper-Scissors output

Code:

#include<iostream>
#include<stdlib.h>
#include<ctime>
using namespace std;
int main()
{
    int n;
    do{
        cout<<"\n\nChoose:\n1. Rock\n2. Paper\n3. Scissors\n4. Exit game";
        cout<<"\nEnter your choice: ";
        cin>>n;
        srand((unsigned) time(0));
        int random = 1 + (rand() % 3);
        if(n<=3)
            cout<<"\tYour choice-"<<n<<" Computer's choice- "<<random<<"\n";
        if(n>4)
            cout<<"Invalid choice";
        else if(n==4)
            cout<<"Exit!";
        else if(n==random)
            cout<<"Tie!";
        else if((n==1)&&(random==3))
            cout<<"You win!";
        else if((n==2)&&(random==1))
            cout<<"You win!";
        else if((n==3)&&(random==2))
            cout<<"You win!";
        else
            cout<<"Computer wins!";
    }while(n!=4);
    return 0;
}

Explanation

The logic behind this is to compare your and computer’s choices to decide the result. This is done using the rules of game as if…else conditions. The computer’s choice is auto generated by using rand() and srand() for which we need <ctime> library. Then comparison is done between both numbers. If your choice is less than 4 then we proceed else it’s an invalid choice. If choice is valid then it checks whether it satisfies any of the if statements and displays the result mentioned in each.

Conclusion

So those were the basic steps to make a rock, paper, scissors game in C++. Share it with your programming buddies and friends. If you have any doubt, mention in the comment section. And for daily updates follow us on Instagram.

Also visit: Tic-Tac-Toe in C++

Visit again for more such programs!

ErrorFreeProgram.

Leave a Reply

Your email address will not be published. Required fields are marked *