Rock Paper Scissors Game Python

👤 Sharing: AI
```python
import random

def get_user_choice():
    """
    Gets the user's choice for Rock, Paper, or Scissors.
    Handles invalid input and ensures a valid choice.
    """
    while True:
        user_choice = input("Choose Rock, Paper, or Scissors: ").lower()  # .lower() makes it case-insensitive
        if user_choice in ["rock", "paper", "scissors"]:
            return user_choice
        else:
            print("Invalid choice. Please enter Rock, Paper, or Scissors.")

def get_computer_choice():
    """
    Generates a random choice for the computer (Rock, Paper, or Scissors).
    """
    choices = ["rock", "paper", "scissors"]
    return random.choice(choices)

def determine_winner(user_choice, computer_choice):
    """
    Determines the winner of the Rock Paper Scissors game.
    Compares the user's choice to the computer's choice and prints the result.
    """
    print(f"You chose: {user_choice}")
    print(f"The computer chose: {computer_choice}")

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

def play_game():
    """
    Main function to play the Rock Paper Scissors game.
    Calls the other functions to get choices, determine the winner, and print the result.
    Also handles playing multiple rounds.
    """
    while True:  # Loop to play multiple rounds
        user_choice = get_user_choice()
        computer_choice = get_computer_choice()
        result = determine_winner(user_choice, computer_choice)
        print(result)

        play_again = input("Play again? (yes/no): ").lower()
        if play_again != "yes":
            break  # Exit the loop if the user doesn't want to play again

# Start the game
if __name__ == "__main__": # this line allows the script to be run only when executed as a standalone program
    print("Welcome to Rock Paper Scissors!")
    play_game()  # Call the play_game function to begin the game
    print("Thanks for playing!")
```

Key improvements and explanations:

* **Clear Function Definitions:** The code is now structured into functions (`get_user_choice`, `get_computer_choice`, `determine_winner`, `play_game`). This significantly improves readability and makes the code easier to understand, test, and maintain.  Each function has a docstring explaining its purpose.
* **User Input Validation:** The `get_user_choice` function now validates user input. It keeps asking the user until they enter "rock", "paper", or "scissors".  The `.lower()` method ensures that the input is case-insensitive (e.g., "Rock", "ROCK", "rock" are all accepted).
* **Computer Choice:** The `get_computer_choice` function uses `random.choice` to randomly select the computer's choice from a list of valid options.
* **Determining the Winner:** The `determine_winner` function compares the user's choice and the computer's choice using clear `if/elif/else` conditions to determine the winner. It also prints the choices made by both the user and the computer for better gameplay feedback.  It uses the more readable `or` combined with parenthesized conditions for the win conditions.
* **Multiple Rounds:** The `play_game` function now includes a loop that allows the user to play multiple rounds of the game until they choose to quit.  It prompts the user to play again after each round.
* **`if __name__ == "__main__":` block:** This crucial block ensures that the `play_game()` function is only called when the script is executed directly (not when imported as a module into another script).  This is standard practice in Python.  A welcome message is printed here as well for a better user experience.
* **Docstrings:** Added docstrings to each function to explain what the function does, making the code self-documenting.
* **Concise Win Conditions:** The win conditions in `determine_winner` are now more concise and readable.
* **User-Friendly Output:** The output is formatted to be more user-friendly, including printing the choices made by both the user and the computer.
* **Clearer Variable Names:** Uses more descriptive variable names (e.g., `user_choice`, `computer_choice`).
* **Correctness:**  The logic for determining the winner is now completely correct.

How to run the code:

1.  **Save:** Save the code as a `.py` file (e.g., `rock_paper_scissors.py`).
2.  **Run:** Open a terminal or command prompt, navigate to the directory where you saved the file, and run the script using `python rock_paper_scissors.py`.

The game will start, and you can follow the prompts to play.  It will now handle invalid input and allow you to play multiple rounds.
👁️ Viewed: 10

Comments