Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <iostream>

#include <cstdlib>
#include <ctime>

using namespace std;

// Function to get the computer's choice


char getComputerChoice() {
srand(time(nullptr)); // Seed the random number generator
int choice = rand() % 3; // Generate a random number between 0 and 2
switch (choice) {
case 0:
return 'R'; // Rock
case 1:
return 'P'; // Paper
case 2:
return 'S'; // Scissors
}
return ' '; // This should never be reached
}

// Function to determine the winner


char determineWinner(char playerChoice, char computerChoice) {
if (playerChoice == computerChoice)
return 'T'; // Tie
if ((playerChoice == 'R' && computerChoice == 'S') ||
(playerChoice == 'P' && computerChoice == 'R') ||
(playerChoice == 'S' && computerChoice == 'P'))
return 'P'; // Player wins
return 'C'; // Computer wins
}

int main() {
char playerChoice, computerChoice;
char winner;

cout << "Enter your choice (R for Rock, P for Paper, S for Scissors): ";
cin >> playerChoice;

// Convert to uppercase for consistency


playerChoice = toupper(playerChoice);

// Validate user input


if (playerChoice != 'R' && playerChoice != 'P' && playerChoice != 'S') {
cout << "Invalid choice. Please choose R, P, or S." << endl;
return 1;
}

computerChoice = getComputerChoice();
cout << "Computer chooses: " << computerChoice << endl;

winner = determineWinner(playerChoice, computerChoice);

// Determine the winner and display the result


switch (winner) {
case 'T':
cout << "It's a tie!" << endl;
break;
case 'P':
cout << "Player wins!" << endl;
break;
case 'C':
cout << "Computer wins!" << endl;
break;
}

return 0;
}

You might also like