Skip to content

Building a Rock Paper Scissors Game in Python

Updated: at 03:23 AM

Rock paper scissors is a classic hand game that is commonly used as an educational tool for teaching basic programming logic and fundamentals. By building a rock paper scissors game in Python, developers can learn core programming concepts like variables, conditionals, loops, functions, and modules in a hands-on and engaging way.

In this comprehensive guide, we will walk through the key steps and considerations for developing a fully-functional rock paper scissors game in Python. The guide includes example code snippets and explanations to illustrate Python programming techniques and best practices.

Table of Contents

Open Table of Contents

Overview of Rock Paper Scissors Game Logic

The rock paper scissors game pits two players against each other, where each player simultaneously forms one of three shapes with their hands:

The rules are:

If both players choose the same shape, the game results in a tie.

The gameplay involves luck and psychology as players try to outwit their opponent.

To implement this in Python, we need to:

We will use Python’s random module to randomly generate the computer’s choice. Conditionals and loops will implement the rules to determine the winner. Functions will structure the code into logical blocks.

Importing Modules

All Python programs start by importing the modules needed. For our game, we only need Python’s built-in random module:

import random

The random module contains functions for generating pseudorandom numbers and making random selections. We will use it to randomly select the computer’s gesture.

Game Variables and Data Structures

Next, we define the variables and data structures to store the game data:

player_name = "Player 1" # Store player's name

choices = ["rock", "paper", "scissors"] # List of valid choices

player_wins = 0 # Player win count
computer_wins = 0 # Computer win count

We use a list choices to store the valid options as string values “rock”, “paper”, and “scissors”.

Two integer variables player_wins and computer_wins will keep track of scores.

Game Functions

To better organize the code, we will build the game logic inside functions:

Get Player Choice

First, a function to get the player’s choice:

def get_player_choice():

  # Ask for player input
  player_choice = input("(r)ock, (p)aper, (s)cissors? ").lower()

  # Validate input
  while player_choice not in ["r", "p", "s"]:
    player_choice = input("Invalid choice. Please enter r, p, or s: ")

  # Return choice
  if player_choice == "r":
    return "rock"
  elif player_choice == "p":
    return "paper"
  elif player_choice == "s":
    return "scissors"

We take the player’s input, convert it to lower case, and validate it is ‘r’, ‘p’, or ‘s’. Then we return the corresponding string value “rock”, “paper”, or “scissors”.

Get Computer Choice

Next, a function to randomly generate the computer’s choice:

import random

def get_computer_choice():

  # Use randint function to get a random index for list choice
  choice_index = random.randint(0,len(choices)-1)

  # Return choice from list using index
  return choices[choice_index]

random.randint() returns a random integer between the given range. We use it to grab a random index for the choices list, then return that string element.

Determine Winner

This function will compare the player and computer choices using if/elif/else conditionals to determine the winner based on the game rules:

def determine_winner(player_choice, computer_choice):

  # Compare choices
  if player_choice == computer_choice:
    winner = "Tie"
  elif player_choice == "rock":
    if computer_choice == "scissors":
      winner = "Player"
    else:
      winner = "Computer"
  elif player_choice == "paper":
    if computer_choice == "rock":
      winner = "Player"
    else:
      winner = "Computer"
  elif player_choice == "scissors":
    if computer_choice == "paper":
      winner = "Player"
    else:
      winner = "Computer"

  # Return winner
  return winner

Based on the possible combinations, we set winner to either “Player”, “Computer” or “Tie” and return that result.

Update Score

After each round we need to update the score:

def update_score(winner):

  # Global variables to update
  global player_wins
  global computer_wins

  if winner == "Player":
    # Increment player win count
    player_wins += 1
  elif winner == "Computer":
    # Increment computer win count
    computer_wins += 1

By declaring player_wins and computer_wins as global variables, we can update their values inside the function.

Once the game loop ends, we can print the final winner:

def print_final_winner():

  # Print final score
  print("\nFINAL SCORE:")
  print(f"Player Wins: {player_wins}")
  print(f"Computer Wins: {computer_wins}")

  # Print winner
  if player_wins > computer_wins:
    print("CONGRATS, YOU WIN!")
  elif player_wins < computer_wins:
    print("OH NO, THE COMPUTER WON...")
  else:
    print("IT'S A TIE!")

This prints the final score and winner message based on who won more rounds.

Main Game Loop

With the functions defined, we can now implement the main game loop:

while True:

  # Get player input
  print("\nPlayer Turn:")
  player_choice = get_player_choice()

  # Get computer choice
  print("Computer's Turn:")
  computer_choice = get_computer_choice()

  # Determine winner
  winner = determine_winner(player_choice, computer_choice)

  # Print round winner
  print(f"Round Winner: {winner}")

  # Update score
  update_score(winner)

  # Ask to play again
  play_again = input("Play again (y/n)? ")

  # Break loop if user does not want to play
  if play_again.lower() != "y":
    break

# Print final score and winner
print_final_winner()

The while True loop continues until the player enters ‘n’ to quit.

Inside the loop we get the player and computer choices, determine the round winner, update scores, and ask if the player wants to continue.

After breaking the loop, we call print_final_winner() to print the game results.

Complete Code

The full rock paper scissors game code looks like:

import random

# Game variables
player_name = "Player 1"
choices = ["rock", "paper", "scissors"]
player_wins = 0
computer_wins = 0


# Functions

def get_player_choice():
  # Get input
  player_choice = input("(r)ock, (p)aper, (s)cissors? ").lower()

  # Validate input
  while player_choice not in ["r", "p", "s"]:
    player_choice = input("Invalid choice. Please enter r, p, or s: ")

  # Return choice
  if player_choice == "r":
    return "rock"
  elif player_choice == "p":
    return "paper"
  elif player_choice == "s":
    return "scissors"

def get_computer_choice():
  # Get random index from choices list
  choice_index = random.randint(0,len(choices)-1)
  # Return choice
  return choices[choice_index]

def determine_winner(player_choice, computer_choice):
  # Compare choices
  if player_choice == computer_choice:
    winner = "Tie"
  elif player_choice == "rock":
    if computer_choice == "scissors":
      winner = "Player"
    else:
      winner = "Computer"
  elif player_choice == "paper":
    if computer_choice == "rock":
      winner = "Player"
    else:
      winner = "Computer"
  elif player_choice == "scissors":
    if computer_choice == "paper":
      winner = "Player"
    else:
      winner = "Computer"

  return winner

def update_score(winner):
  global player_wins
  global computer_wins
  if winner == "Player":
    player_wins += 1
  elif winner == "Computer":
    computer_wins += 1

def print_final_winner():
  print("\nFINAL SCORE:")
  print(f"Player Wins: {player_wins}")
  print(f"Computer Wins: {computer_wins}")

  if player_wins > computer_wins:
    print("CONGRATS, YOU WIN!")
  elif player_wins < computer_wins:
    print("OH NO, THE COMPUTER WON...")
  else:
    print("IT'S A TIE!")

# Main game loop
while True:

  print("\nPlayer Turn:")
  player_choice = get_player_choice()

  print("Computer's Turn:")
  computer_choice = get_computer_choice()

  winner = determine_winner(player_choice, computer_choice)

  print(f"Round Winner: {winner}")

  update_score(winner)

  play_again = input("Play again (y/n)? ")

  if play_again.lower() != "y":
    break

print_final_winner()

The code is organized into logical blocks, uses descriptive variable names, and contains comments explaining each part. Proper code structure and formatting makes the program easy to understand.

Running and Testing the Game

To test the game, run the code in a Python interpreter or Jupyter notebook. The game loop will continue until you enter ‘n’ to quit:

Player Turn:
(r)ock, (p)aper, or (s)cissors? r

Computer's Turn:
Round Winner: Player

Play again (y/n)? y

Player Turn:
(r)ock, (p)aper, or (s)cissors? s

Computer's Turn:
Round Winner: Computer

Play again (y/n)? n

FINAL SCORE:
Player Wins: 1
Computer Wins: 1
IT'S A TIE!

The input is validated each turn, and the winner is correctly calculated based on random choices. Scores increment properly after each round.

To fully test the game, play through multiple times and verify that winners are determined correctly in all cases. Try inputting invalid choices to test the error handling.

The completed game can be executed repetitively while keeping score, providing an interactive Python programming experience.

Example Use Cases

Rock paper scissors provides a fun way to learn Python programming. Some example use cases include:

Computer Science Education - The game logic exemplifies conditional statements, variables, functions, loops, input/output, and randomness. Creating the program helps reinforce core CS concepts.

Tech Interviews - Implementing rock paper scissors is a common technical interview question. The game tests a candidate’s Python proficiency.

AI Training - With some enhancements, rock paper scissors can teach AI systems strategic decision making. The trained neural networks study human gameplay to optimize win rate.

Gaming and Simulations - The game mechanics translate well to GUI interfaces using graphics/animations. Real-time user input creates an engaging gameplay experience.

Online Multiplayer - By networking two rock paper scissors programs, players across the internet can compete against each other. This explores socket programming and network communication concepts.

The simple game serves as the foundation for various learning projects, simulations, experiments, and applications.

Summary

Developing a rock paper scissors game in Python reinforces core programming skills like variables, functions, conditionals, loops, data structures, and randomness. The full code example demonstrates proper structure, style, and commenting for writing clean Python programs.

With the game logic coded into separate functions, new features can be easily added, such as a GUI, AI opponent, or online multiplayer. The documentation and explanations provided here serve as a comprehensive guide for anyone learning Python through this classic programming exercise.

The hands-on coding tutorial explores the key steps and considerations when building a fully-functional rock paper scissors game using Python. Readers should now have the knowledge to create their own complete implementation.