Day 22: Rock, Paper, Scissors Game

Objective

Your task today is to create a simple Rock, Paper, Scissors game. The user will play against the computer, which will randomly select one of the three options. The program will determine the winner based on the rules of the game.

The rules are:

  1. Rock beats Scissors
  2. Scissors beats Paper
  3. Paper beats Rock

For example:

  • Input: User chooses “Rock”; Computer chooses “Scissors”.
  • Output: “You win! Rock beats Scissors.”

Why This Challenge Is Important

This challenge combines many concepts you’ve learned so far, including:

  • Taking user input.
  • Generating random numbers or choices.
  • Using conditional statements to determine outcomes.
  • Writing clean, modular, and reusable code.

It’s also a fun way to practice logic and interact with your code more dynamically.


Steps to Solve

1. Understand the Problem

  • The game consists of three moves: Rock, Paper, and Scissors.
  • The computer randomly selects one move.
  • The user inputs their choice.
  • The program compares the two choices to determine the winner.

2. Plan Your Solution

  1. Import any necessary libraries (e.g., random for Python).
  2. Prompt the user for their choice (Rock, Paper, or Scissors).
  3. Generate the computer’s random choice.
  4. Compare the user’s choice and the computer’s choice to determine the winner.
  5. Display the result.
  6. Allow the user to play multiple rounds.

3. Enhancements to Consider

  • Keep track of the score (e.g., wins, losses, and ties).
  • Add input validation to ensure the user enters a valid choice.
  • Allow the user to quit the game when they’re done.

Code Examples

Python Example

Basic Rock, Paper, Scissors Game

import random

# Define valid choices
choices = ["rock", "paper", "scissors"]

print("Welcome to Rock, Paper, Scissors!")
while True:
    # Get the user's choice
    user_choice = input("Enter Rock, Paper, or Scissors (or 'quit' to stop): ").lower()

    # Exit the game if the user types 'quit'
    if user_choice == "quit":
        print("Thanks for playing!")
        break

    # Validate the user's choice
    if user_choice not in choices:
        print("Invalid choice. Please try again.")
        continue

    # Generate the computer's choice
    computer_choice = random.choice(choices)
    print(f"The computer chose: {computer_choice}")

    # Determine the winner
    if user_choice == computer_choice:
        print("It's a tie!")
    elif (user_choice == "rock" and computer_choice == "scissors") or \
         (user_choice == "scissors" and computer_choice == "paper") or \
         (user_choice == "paper" and computer_choice == "rock"):
        print("You win!")
    else:
        print("You lose!")

    print()

Java Example

Basic Rock, Paper, Scissors Game

import java.util.Random;
import java.util.Scanner;

public class RockPaperScissors {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();
        String[] choices = {"rock", "paper", "scissors"};

        System.out.println("Welcome to Rock, Paper, Scissors!");

        while (true) {
            // Get user input
            System.out.print("Enter Rock, Paper, or Scissors (or 'quit' to stop): ");
            String userChoice = scanner.nextLine().toLowerCase();

            // Exit the game if the user types 'quit'
            if (userChoice.equals("quit")) {
                System.out.println("Thanks for playing!");
                break;
            }

            // Validate user input
            boolean isValid = userChoice.equals("rock") || userChoice.equals("paper") || userChoice.equals("scissors");
            if (!isValid) {
                System.out.println("Invalid choice. Please try again.");
                continue;
            }

            // Generate the computer's choice
            String computerChoice = choices[random.nextInt(3)];
            System.out.println("The computer chose: " + computerChoice);

            // Determine the winner
            if (userChoice.equals(computerChoice)) {
                System.out.println("It's a tie!");
            } else if ((userChoice.equals("rock") && computerChoice.equals("scissors")) ||
                       (userChoice.equals("scissors") && computerChoice.equals("paper")) ||
                       (userChoice.equals("paper") && computerChoice.equals("rock"))) {
                System.out.println("You win!");
            } else {
                System.out.println("You lose!");
            }

            System.out.println();
        }
    }
}

JavaScript Example

Basic Rock, Paper, Scissors Game

console.log("Welcome to Rock, Paper, Scissors!");

const choices = ["rock", "paper", "scissors"];

while (true) {
    // Get the user's choice
    let userChoice = prompt("Enter Rock, Paper, or Scissors (or 'quit' to stop):").toLowerCase();

    // Exit the game if the user types 'quit'
    if (userChoice === "quit") {
        console.log("Thanks for playing!");
        break;
    }

    // Validate the user's choice
    if (!choices.includes(userChoice)) {
        console.log("Invalid choice. Please try again.");
        continue;
    }

    // Generate the computer's choice
    let computerChoice = choices[Math.floor(Math.random() * 3)];
    console.log(`The computer chose: ${computerChoice}`);

    // Determine the winner
    if (userChoice === computerChoice) {
        console.log("It's a tie!");
    } else if (
        (userChoice === "rock" && computerChoice === "scissors") ||
        (userChoice === "scissors" && computerChoice === "paper") ||
        (userChoice === "paper" && computerChoice === "rock")
    ) {
        console.log("You win!");
    } else {
        console.log("You lose!");
    }

    console.log();
}

Edge Cases to Consider

  1. Invalid Input: Handle cases where the user enters an invalid choice.
  2. Case Sensitivity: Normalize user input to lowercase to avoid mismatches.
  3. Ties: Ensure the program correctly handles ties.
  4. Quitting: Provide a clear way for the user to exit the game.

Extensions to Explore

  1. Keep Score: Track wins, losses, and ties over multiple rounds.
  2. Advanced Computer AI: Use probability to make the computer’s choices more strategic.
  3. Customizable Options: Allow the user to add moves like “Lizard” or “Spock” (as in the extended Rock-Paper-Scissors game).

What You’ve Learned

  • How to use randomization to create dynamic behavior in your programs.
  • How to write conditional logic to compare inputs and determine outcomes.
  • How to create an interactive program for user input and feedback.

Next Steps

In Day 23: Simple Login System, you’ll build a simple login system where users can register and then log in by entering their username and password. This task will introduce you to concepts such as storing user data, validating input, and ensuring security basics.