Adventures in Machine Learning

Python Rock Paper Scissors: Play Against a Friend or the Computer

Rock Paper Scissors is a classic hand game enjoyed by two or more players. The game is simple yet extremely addictive, with players competing to choose one of three options: rock, paper, or scissors.

In this article, we will discuss the rules of the game, how to play, and how to build the game in Python.

How to Play the Game:

The rules of Rock Paper Scissors are straightforward.

Each player uses their hand to form one of three gestures: rock (a closed fist), paper (an open hand), and scissors (a fist with the index and middle fingers extended). The objective of the game is to select the gesture that will beat the other player’s gesture.

The outcome is determined by the following rules:

  • Rock beats scissors (rock smashes scissors)
  • Scissors beat paper (scissors cut paper)
  • Paper beats rock (paper covers rock)

The game is typically played in rounds, with players making gestures simultaneously. Each round results in one of three outcomes: a win, a loss, or a tie.

To keep the game moving, players usually play multiple rounds until a winner is determined.

Building Rock Paper Scissors in Python:

To build the game in Python, we will be using several built-in modules.

The first module we will use is the random module, which allows us to generate random integers. We will also use the getpass module as a way to hide each player’s input when entering their chosen gesture.

Before we begin coding, let’s create a friendly message for each player to see. This can be done by using a print statement for each player’s greeting.

For example:

player1_name = input("What is your name, Player 1? ")
player2_name = input("What is your name, Player 2? ")
print("Hello, " + player1_name + " and " + player2_name + " let's play Rock Paper Scissors!")

Now, let’s get started with building the game. We will begin by defining a function, play_game():

import random
import getpass

def play_game():
  player_a_choice = getpass.getpass("Player 1, enter your choice (rock/paper/scissors): ")
  player_b_choice = getpass.getpass("Player 2, enter your choice (rock/paper/scissors): ")
  while player_a_choice == player_b_choice:
    print("It's a tie! Try again.")
    player_a_choice = getpass.getpass("Player 1, enter your choice (rock/paper/scissors): ")
    player_b_choice = getpass.getpass("Player 2, enter your choice (rock/paper/scissors): ")
  if (player_a_choice == "rock" and player_b_choice == "scissors") or (player_a_choice == "scissors" and player_b_choice == "paper") or (player_a_choice == "paper" and player_b_choice == "rock"):
    print("Player 1 wins!")
  else:
    print("Player 2 wins!")

The getpass() function is used to prompt the user for their input without displaying it on the screen. We use a while loop to handle situations where both players choose the same gesture and the round ends in a tie.

When a winner is determined, the game will print a message stating who won.

Conclusion:

In conclusion, Rock Paper Scissors is an enjoyable and simple game that can be played by people of all ages.

Now that you know the rules of the game and how to build it in Python, you can challenge your friends to a game or customize it into something even more exciting. So go ahead and give it a try!

3) Printing Greeting Messages and Asking the Player About How It Wants to Play the Game:

Playing games is one of the easiest ways to get bored time-consuming, but it is also one of the best sources of entertainment.

Amongst all the popular games that we come across every day, one of the most widely played games is Rock Paper Scissors. It is a perfect game for two people to pass the time, and it is also easy to learn.

In this article, we will look at how you can play this classic hand game, but with a new twist. We’ll also introduce you to a Python script that allows you to play this game on your computer.

First, let’s print some greeting messages and provide instruction on how to play the game. The function info() can be used to print the greeting message along with the game rules.

The following code will print the message and ask the player if they want to play with a friend or the computer, and how many rounds they want to play:

import random

def info():
    print ("Welcome to Rock Paper Scissors game!nThis is a hand game meant for two players. Each player forms one of three gestures with their hands.nThe winner is determined by the rules given below:n- Rock smashes scissorsn- Scissors cuts papern- Paper covers rocknYou can choose to play with a friend or the computer. If you choose to play with the computer, enter cpu as the name of the second player.n")            

info()

Now, let’s ask the player about the method of playing the game and the number of rounds they want to play. We can define another function called player_choice() that will ask the player to choose between a human opponent or the computer:

def player_choice():
  x = ""
  while x!= "1" and x!= "2":
    x = input("Enter 1 to play with a friend or 2 to play with the computer: ")
  return int(x)

num_rounds = int(input("How many rounds do you want to play? "))
print("You want to play " + str(num_rounds) + " rounds")
player = player_choice()

4) Creating Separate Functions for Various Purposes:

Now that the greeting messages are printed, and the player has chosen the method of playing, we can create three separate functions as follows:

A) Defining the Function to Draw the Hand Diagrams:

To make the game more visually appealing, let us first define a function that takes the user input and displays the hand diagram of the choice made by them. We will use Unicode characters to display the hand diagrams.

The following code will define the draw() function that will print the hand diagrams for rock, paper, and scissors:

def draw(player_choice):
  if player_choice == "rock":
    print("     _______n---'    ____)n       (_____)n       (_____)n       (____)n---.__(___)")
  elif player_choice == "paper":
    print("     _______n---'    ____)____n           ______)n          _______)n         _______)n---.__________)")
  elif player_choice == "scissors":
    print("     _______n---'    ____)____n           ______)n        __________)n       (____)n---.__(___)")

B) Defining the Function to Play with the Computer:

The play_game_with_computer() function will be used to play the game with the computer. This function will display a message for the computer to make a random choice, and the winner of each round will be determined based on the rules given above.

After each round, it will display the score. This function will use the draw() function to display the hand diagrams of the player and the computer.

The following code will define the play_game_with_computer() function:

def play_game_with_computer():
  print("You are playing with the computer")
  player1 = input("Enter your name: ")
  score_player1 = 0
  score_cpu = 0
  for i in range(num_rounds):
    print("nROUND: ", i+1)
    player2 = "cpu"
    x = ""
    while x != "rock" and x != "paper" and x != "scissors":
      x = input(str(player1) + ", Choose rock, paper or scissors: ").lower()
    draw(x)
    cpu = random.choice(['rock', 'paper', 'scissors'])
    print("nComputer chooses: " + cpu)
    draw(cpu)
    if (x == "rock" and cpu == "scissors") or (x == "scissors" and cpu == "paper") or (x == "paper" and cpu == "rock"):
      score_player1 += 1
      print(player1 + " wins this round!")
    elif (x == cpu):
      print("Tie!" )
    else:
      score_cpu += 1
      print("Computer wins this round!")
    print(player1 + "'s score: " + str(score_player1))
    print("Computer's score: " + str(score_cpu))
  if score_player1 > score_cpu:
    print(player1 + " wins the game!")
  elif score_player1 == score_cpu:
    print("It's a tie!")
  else:
    print("Computer wins the game!")

C) Defining the Function to Play Along with a Friend:

The play_game_with_friend() function will be used to play the game with a human opponent. This function will ask the second player for their choice and hide the first player’s response while they make their choice.

The winner of each round will be determined based on the rules given above. After each round, the score will be displayed.

This function will also use the draw() function to display the hand diagrams of both the players. The following code will define the play_game_with_friend() function:

def play_game_with_friend():
  print("You are playing with a friend")
  player1 = input("Enter your name: ")
  player2 = input("Enter the name of your friend: ")
  score_player1 = 0
  score_player2 = 0
  for i in range(num_rounds):
    print("nROUND: ", i+1)
    x = ""
    while x != "rock" and x != "paper" and x != "scissors":
      x = input(str(player1) + ", Choose rock, paper or scissors: ").lower()
    print("Hiding response....n"*10)
    y = ""
    while y != "rock" and y != "paper" and y != "scissors":
      y = input(str(player2) + ", Choose rock, paper or scissors: ").lower()
    draw(x)
    draw(y)
    if (x == "rock" and y == "scissors") or (x == "scissors" and y == "paper") or (x == "paper" and y == "rock"):
      score_player1 += 1
      print(player1 + " wins this round!")
    elif (x == y):
      print("Tie!" )
    else:
      score_player2 += 1
      print(player2 + " wins this round!")
    print(player1 + "'s score: " + str(score_player1))
    print(player2 + "'s score: " + str(score_player2))
  if score_player1 > score_player2 :
    print(player1 + " wins the game!")
  elif score_player1 == score_player2:
    print("It's a tie!")
  else:
    print(player2 + " wins the game!")

Conclusion:

In conclusion, playing games is an excellent way to pass time and have fun, especially if it is too hot, too cold, or too rainy outside.

Rock Paper Scissors is a game that people of all ages can play and enjoy. Taking things a level further, we have introduced a Python script that will let you play this game on your computer.

We have provided you with a simple step-by-step guide to play the game with a human opponent or the computer. With the use of separate functions, the game has been made more interactive, engaging, and visually appealing.

We hope this article has been helpful, and you enjoy playing this game.

5) Final Outputs:

Now that we have defined all the necessary functions, let’s run the game and see the sample results.

Below is the sample output for playing the game with a friend:

Welcome to Rock Paper Scissors game!
This is a hand game meant for two players. Each player forms one of three gestures with their hands.

The winner is determined by the rules given below:
- Rock smashes scissors
- Scissors cuts paper
- Paper covers rock
You can choose to play with a friend or the computer. If you choose to play with the computer, enter cpu as the name of the second player.

How many rounds do you want to play? 3

You want to play 3 rounds
Enter 1 to play with a friend or 2 to play with the computer: 1

You are playing with a friend
Enter your name: Alex
Enter the name of your friend: John
ROUND:  1
Alex, Choose rock, paper or scissors: rock
Hiding response....      
---.__(___)
     
---'    ____)____
           ______)
          _______)
         _______)
---.__________)
Alex wins this round!
Alex's score: 1
John's score: 0
ROUND:  2
Alex, Choose rock, paper or scissors: paper
Hiding response....
     
---'    ____)(_______
       (_____)(_______
       (_____)(_______
       (______)(_______
---.__(___)(__________)
     
---'    ____)____
           ______)
        __________)
       (____)
---.__(___)
Alex wins this round!
Alex's score: 2
John's score: 0
ROUND:  3
Alex, Choose rock, paper or scissors: scissors
Hiding response....      
     _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
     
     _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
Tie!
Alex's score: 2
John's score: 0
Alex wins the game!

As shown in the example, the game has run for three rounds, and Alex has won two rounds, while John hasn’t won any, and one round ended in a tie. As a result, Alex wins the game.

Similarly, suppose the player has chosen to play with the computer. In that case, the results of the game will be determined based on the computer’s choices, as shown in the following sample output:

Welcome to Rock Paper Scissors game!
This is a hand game meant for two players. Each player forms one of three gestures with their hands.

The winner is determined by the rules given below:
- Rock smashes scissors
- Scissors cuts paper
- Paper covers rock
You can choose to play with a friend or the computer. If you choose to play with the computer, enter cpu as the name of the second player.

How many rounds do you want to play? 4

You want to play 4 rounds
Enter 1 to play with a friend or 2 to play with the computer: 2

You are playing with the computer
Enter your name: Alex
ROUND:  1
Alex, Choose rock, paper or scissors: paper
     
     _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
Computer chooses: rock
     
     _______
---'    ____)(_______
       (_____)(_______
       (_____)(_______
       (______)(_______
---.__(___)(__________)
Alex wins this round!
Alex's score: 1
Computer's score: 0
ROUND:  2
Alex, Choose rock, paper or scissors: rock
     
---.__(___)
     
---'    ____)____
           ______)
          _______)
         _______)
---.__________  
Computer chooses: scissors
     
     _______
---'    ____)____
           ______)
        __________)
       (____)
---.__(___)
Alex wins this round!
Alex's score: 2
Computer's score: 0
ROUND:  3
Alex, Choose rock, paper or scissors: scissors
     
     _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
Computer chooses: scissors
     
     _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
Tie!
Alex's score: 2
Computer's score: 0
ROUND:  4
Alex, Choose rock, paper or scissors: rock
     
---.__(___)
Computer chooses: paper
     
     _______
---'   

Popular Posts