w3resource

Python Project - Rock, Paper, Scissors Game: Solutions and Explanations


Rock, Paper, Scissors Game:

Implement the classic game with a user interface.

From Wikipedia - Rock paper scissors (commonly scissors, paper, rock or stone in Australia and New Zealand) is an intransitive hand game, usually played between two people, in which each player simultaneously forms one of three shapes with an outstretched hand. These shapes are "rock" (a closed fist), "paper" (a flat hand), and "scissors" (a fist with the index finger and middle finger extended, forming a V). The earliest form of "rock paper scissors"-style game originated in China and was subsequently imported into Japan, where it reached its modern standardized form, before being spread throughout the world in the early 20th century.

Input values:
Player selects rock, paper, or scissors.

Output value:
Result of the game, indicating whether the player wins, loses, or it's a tie.

Example:

Input values:
Select your move (1 for Rock, 2 for Paper, 3 for Scissors): 2
Output value:
Computer chose Rock. You win!
Input values:
Select your move (1 for Rock, 2 for Paper, 3 for Scissors): 1
Output value:
Computer chose Scissors. You lose!
Input values:
Select your move (1 for Rock, 2 for Paper, 3 for Scissors): 3
Output value:
Computer chose Paper. It's a tie!

Here are two different solutions for the "Rock, Paper, Scissors" game in Python. This game will allow the player to select rock, paper, or scissors and then determine the outcome based on a random move chosen by the computer.

Solution 1: Basic Approach using Conditional Statements

Code:

# Solution 1: Basic Approach Using Conditional Statements

import random  # Import the random module to allow the computer to make a random choice

def play_game():
    """Function to play a single round of Rock, Paper, Scissors"""
    print("Welcome to Rock, Paper, Scissors!")

    # Define the possible moves
    moves = {1: "Rock", 2: "Paper", 3: "Scissors"}

    # Get the player's move
    player_move = int(input("Select your move (1 for Rock, 2 for Paper, 3 for Scissors): "))

    # Validate player input
    if player_move not in moves:
        print("Invalid input. Please enter 1, 2, or 3.")
        return

    # Randomly select the computer's move
    computer_move = random.randint(1, 3)

    # Display the moves
    print(f"Computer chose {moves[computer_move]}. You chose {moves[player_move]}.")

    # Determine the game outcome using conditional statements
    if player_move == computer_move:
        print("It's a tie!")
    elif (player_move == 1 and computer_move == 3) or \
         (player_move == 2 and computer_move == 1) or \
         (player_move == 3 and computer_move == 2):
        print("You win!")
    else:
        print("You lose!")

# Start the game
play_game()

Output:

Welcome to Rock, Paper, Scissors!
Select your move (1 for Rock, 2 for Paper, 3 for Scissors): 2
Computer chose Scissors. You chose Paper.
You lose!
Welcome to Rock, Paper, Scissors!
Select your move (1 for Rock, 2 for Paper, 3 for Scissors): 1
Computer chose Rock. You chose Rock.
It's a tie!

Explanation:

  • The game is implemented as a single function 'play_game()'.
  • The player selects a move by inputting a number (1 for Rock, 2 for Paper, 3 for Scissors), which is validated for correctness.
  • The computer's move is randomly selected using 'random.randint(1, 3)'.
  • The game outcome is determined by comparing the player's move and the computer's move using a series of conditional statements ('if-elif').
  • The function provides feedback to the player, indicating whether they win, lose, or tie.
  • This solution is simple and effective but has all the logic in a single function, which can make it harder to maintain or extend.

Solution 2: Using a Class to structure the Game Logic

Code:

# Solution 2: Using a Class to Structure the Game Logic

import random  # Import the random module to allow the computer to make a random choice

class RockPaperScissors:
    """Class to handle the Rock, Paper, Scissors game"""

    def __init__(self):
        """Initialize the game with available moves"""
        self.moves = {1: "Rock", 2: "Paper", 3: "Scissors"}
        print("Welcome to Rock, Paper, Scissors!")

    def get_player_move(self):
        """Prompt the player for their move"""
        try:
            # Get player input
            player_move = int(input("Select your move (1 for Rock, 2 for Paper, 3 for Scissors): "))
            # Check if the move is valid
            if player_move not in self.moves:
                print("Invalid input. Please enter 1, 2, or 3.")
                return None
            return player_move
        except ValueError:
            print("Invalid input. Please enter a number.")
            return None

    def get_computer_move(self):
        """Randomly generate the computer's move"""
        return random.randint(1, 3)

    def determine_winner(self, player_move, computer_move):
        """Determine the result of the game based on player and computer moves"""
        print(f"Computer chose {self.moves[computer_move]}. You chose {self.moves[player_move]}.")

        # Determine the game outcome
        if player_move == computer_move:
            print("It's a tie!")
        elif (player_move == 1 and computer_move == 3) or \
             (player_move == 2 and computer_move == 1) or \
             (player_move == 3 and computer_move == 2):
            print("You win!")
        else:
            print("You lose!")

    def play(self):
        """Run the game"""
        player_move = self.get_player_move()
        if player_move:
            computer_move = self.get_computer_move()
            self.determine_winner(player_move, computer_move)

# Create an instance of the RockPaperScissors class and start the game
game = RockPaperScissors()
game.play()

Output:

Welcome to Rock, Paper, Scissors!
Select your move (1 for Rock, 2 for Paper, 3 for Scissors): 3
Computer chose Paper. You chose Scissors.
You win!
Welcome to Rock, Paper, Scissors!
Select your move (1 for Rock, 2 for Paper, 3 for Scissors): 1
Computer chose Rock. You chose Rock.
It's a tie!

Explanation:

  • The game is encapsulated within a RockPaperScissors class, which makes the code more modular and organized.
  • The class has methods to handle different parts of the game, such as:
    • get_player_move() for prompting the player and validating input.
    • get_computer_move() for generating the computer's random move.
    • determine_winner() for determining and displaying the game result.
    • play() for running the game.
  • This approach provides a cleaner and more scalable way to manage the game logic, making it easier to add new features or modify existing ones.
  • It leverages Object-Oriented Programming (OOP) principles for better code organization and maintainability.

Note:
Both solutions implement the "Rock, Paper, Scissors" game effectively, with Solution 1 providing a basic, functional approach and Solution 2 using a more structured, class-based design.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/projects/python/python-rock-paper-scissors-game-project.php