1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; // Function to get the computer's choice string getComputerChoice() { int choice = rand() % 3; // Generates a number between 0 and 2 if (choice == 0) return "Rock"; if (choice == 1) return "Paper"; return "Scissors"; } // Function to determine the winner string determineWinner(string playerChoice, string computerChoice) { if (playerChoice == computerChoice) { return "It's a tie!"; } else if ((playerChoice == "Rock" && computerChoice == "Scissors") || (playerChoice == "Paper" && computerChoice == "Rock") || (playerChoice == "Scissors" && computerChoice == "Paper")) { return "You win!"; } else { return "Computer wins!"; } } int main() { srand(static_cast<unsigned int>(time(0))); // Seed the random number generator string playerChoice; cout << "Enter Rock, Paper, or Scissors: "; cin >> playerChoice; // Convert player choice to the first letter capitalized format playerChoice[0] = toupper(playerChoice[0]); for (size_t i = 1; i < playerChoice.length(); ++i) { playerChoice[i] = tolower(playerChoice[i]); } string computerChoice = getComputerChoice(); cout << "Computer chose: " << computerChoice << endl; string result = determineWinner(playerChoice, computerChoice); cout << result << endl; return 0; } |
Explanation
- Random Number Generation:
srand(static_cast<unsigned int>(time(0)));
seeds the random number generator to ensure the computer’s choice is different each time the game is played.
- getComputerChoice Function:
- This function generates a random number between 0 and 2, mapping each number to one of the choices: “Rock”, “Paper”, or “Scissors”. This simulates the computer’s move in the game.
- determineWinner Function:
- This function compares the player’s choice with the computer’s choice to determine the winner based on the rules of Rock, Paper, Scissors:
- Rock beats Scissors
- Paper beats Rock
- Scissors beats Paper
- If both choices are the same, it’s a tie.
- This function compares the player’s choice with the computer’s choice to determine the winner based on the rules of Rock, Paper, Scissors:
- Player Input:
- The player is prompted to enter their choice, which is then processed to ensure the first letter is capitalized, making it easier to compare with the computer’s choice.
- Main Function:
- The
main()
function handles the game loop:- It gets the player’s choice.
- It determines the computer’s choice.
- It prints the computer’s choice.
- It determines and displays the winner.
- The