Rock Paper Scissors Python

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

Building game using programming are a great way to learn programming languages. You get to use tools and design patterns you see in real-world situations. An ideal game to start building games in Python is Rock Paper Scissors. In the article, we will learn to build a Rock Paper Scissor python game using Python programming language. We will start building the project for a single game and later expand the logic to play the game indefinitely.

What Are We Building?

You might have played a rock paper scissors game with your friends before. Possibly to settle a discussion or to decide who will take that window seat in the college tour.

What Are We Building

For those who do not, rock paper scissors games are played between two players with hand gestures. Both participants say "Rock, Paper, Scissors" and then together shape their hands to symbolically show either rock (fist), paper (palm), or scissors (two fingers extended). The winner is decided based on three straightforward rules:

  1. Paper covers rock.
  2. Rock smashes scissors.
  3. Scissors cut paper.

Now that we know the game rules let us start building a Rock Paper Scissors Python game program to simulate the game using computers.

Pre-requisites

To build the Rock Paper Scissors python game, we will use Python language, making it a requirement for this project if you are not familiar with how to write basic programs in Python, including how loops work and take user inputs. We recommend you read about these concepts from here.

How are we going to build the Rock Paper Scissors Python project?

We will start by taking the user input to know the user's choice (rock, paper, or scissors). Following this, we will make the computer choose its choice randomly from the available three gestures. Now that we have both choices (users and computers), based on the game rules, we will decide who the winner of the match is and output the result on the screen.

The project will utilize primary input and output functions along with loops provided by Python. We will also use the random python library to randomly make a choice whether to choose rock, paper, or scissors, which is required to remove biases from the game.

Final Output

Once finished, we will be able to play a game of Rock Paper Scissors using python with the computer, where we will enter our choice (rock, paper, or scissors) in the console, and the computer will make its own choice. Based on the choices made by you and the computer, we will determine the winner of the game. Here is the output of the program which we will build.

Rock Paper Scissors Final Output

Requirements

As previously mentioned, we will require knowledge of Python concepts on how to take user inputs and loops to start building the Rock paper scissors python project. We also use the random python library to make random choices in the code.

In the later sections, we will refactor our Rock paper scissors python program, which will require OOPS concepts in Python. Before reading this article, we recommend you finish these concepts.

Building Rock Paper Scissors Game using Python

To build the Rock paper scissors python game, we will divide the problem statement into three simple steps to help us build the game.

The steps are as follows:

  1. Take the input from the user to know their choice (rock, paper or scissors).
  2. Randomly allow the program to choose its choice.
  3. Based on the game rules, decide the winner and display the winner on the screen.

We will later use the logic to play several games and refactor our Rock paper scissors python program for better readability and edge case handling. Let us start by building the project first by playing a single game.

Algorithm for Single Game

Before we start building our Rock paper scissors python game, we will first be required to import a random module in our program that will help to simulate the program's choice.

Since our user must enter their choice, we will need a way to get the users' input.

1. Taking user's input

In Python, taking the user's input is quite simple. Our goal here is to take the input from the user on which action they would like to choose and then assign the choice to a variable. To take the user input, we can use the following code snippet.

This code snippet prompts users to input their choice from the command line. We assign the choice entered by the user in the variable user_choice.

2. Making the program choose

Now that we have user choice stored in a variable, the next step is deciding on program choice. We will make the computer choose its action randomly. To make a random selection, we use the random.choice() function from the previously imported random module to choose from available three actions.

This code allows the computer to choose a random item from the list. Now, we have the computer and the user's choice stored in variables. We can print these choices.

Printing both choices can be helpful to debug the winners if something is not working correctly.

3. Determine The Winner

Now that we have the information about users' and computer's choices, we can use the game rules to decide the winner. Using the if, elif and else block in Python, we can determine the winner of the game.

Here by comparing the tie condition first, we eliminate several edge conditions that can arise. If we don't do that, we will need to compare every user action to the program's possible choices. Because we checked the time condition in the beginning, we only need now to determine the winner based on different choices the program can make against the user's choice.

With these three steps combined, our program to simulate a game of rock paper scissors between computer and user is finished. In the end, our combined rock paper scissors python program should look like this:

Note: Since we are using string matching here to identify the action user chose, it is important to enter the exact actions string (without spaces) for the program to recognize the action correctly.

Algorithm for Several Games

Now that we have written a program to play a single game of rock, paper, and scissors between user and computer, it's super fun! But wouldn't it be great to play multiple games without a need to rerun the program without the program finishing?

A great choice to create such recurring program are loops; specifically, we can use a while loop in a python program to play the game indefinitely. We can wrap the entire program within a while loop, as shown below, to play several games:

Here, we use a while loop to create a never-ending recurring event. To break out from this indefinite looping condition. At the end of each game, we ask the user whether they want to play again. If the user input n, i.e., 'no' as an answer, we use the break keyword to come out from the infinite recurring loop and stop the program execution. The other way to stop program execution is terminating the program execution from the console using ctrl + c.

Action Description with enum.IntEnum

There is a possibility that the user enters "rocK" instead of "rock". For such inputs, the program will cause a problem. It's a good idea to handle such user inputs to avoid crashes. One possibility is to replace action strings with integers like:

The solution will work well with this change, but a better way to deal with similar situations is to use enum.IntEnum and define our class to use the actions.

enum.IntEnum in Python let us create data attributes and assign them with values similar to the variable approach we showed above. This helps clean up the code and make it more readable using our namespaces.

Here, we created a custom Action that can support and reference different types of actions we wish to support. Comparing action types using them is straightforward and less prone to errors when compared to direct string comparisons.

We can also create actions using integer values from an int:

This way, the Action class is helpful for our case because we can create an Action object by taking the user's integer input and comparing the values.

Hence, we do not need to worry about spelling and character casing now.

Flow Chart of the Program

It is always important to consider all the possibilities before building a project. Flow charts are always an excellent way to understand code flow and get the desired outcome by building the implementation around it. Here is a flow chart for our single game of rock paper scissors:

Flow Chart of the Program

Here, as you can see, our code flow is divided into three steps:

  1. Getting the user selection.
  2. Select the action of a computer.
  3. Determining the winner of the round.

The flow diagram is correct for the single round of the game we have coded, but it is not accurate for real-game situations. In the real world, both players choose their choice simultaneously, but in our coded version, this is correct because we are making computer choices random and independent of the user's choice.

Drawing a flow chart helps us to identify an issue early. From the above flow chart, we know the flow does not have a part where users can choose whether to play the game again. A different flow chart can address this by introducing a choice at the end of every game.

Introducing a Choice at the End of Every Game

This way without even writing code, we can identify possible situations and deal with them early while designing and planning our projects.

Splitting Program into Functions

Now that we have made a flow chart to understand our solution for the game, we can optimize our rock paper scissors python code by building separate code blocks for individual steps in the flow chart. One way of doing this is by creating and using functions in Python. Functions are a great way to make our code readable and easy to handle.

We can start by building an Action class, as discussed in this article.

The next step is to create a separate function to take input from the user like:

Output

Here, we wrap user input inside int() to get the integer choice from the user (instead of string). Notice how we are returning Action from the function. Also, to make our code customizable, we are creating a choice from the actions available in Action. This way, it is easy to add new actions in the program in the future without making any changes to this function.

The next step is to generate a random action to decide the Rock paper scissors python program's choice for the game. Because the choices are from 0 to 2, as we have three choices, we will use random.randint() to generate a random integer between the several choices we have. Our function should not take any argument and return a randomly selected action.

Output

Here, to decide the upper bound of actions, we use the len() function, and because our indexing for actions starts with one, we use len(Action)-1 in our random function.

Next, we need to determine the winner based on choices. This function should take two arguments, user and program choices, and display the winner on the console.

This is similar to the logic we used in our first code iteration. Since we want the user to enter choices in a valid range, we can add a ValueError check in our code to ensure the user always enters a valid parameter.

Also, to deal with the following situation, we will modify our flow chart:

Enter Choices in a Valid Range

Hence, if the user enters an invalid number, we repeat the whole step by asking the input from the user again. We will catch the value error exception raised when a user enters invalid choices. With this, let us combine all the function calls to finish our rock paper scissors python code.

Notice how using the function makes our rock paper scissors python code a lot more readable.

What’s Next

Are you a big band theory fan? If yes, you must be familiar with the rock paper scissor lizard spoke game. If not, here is a diagram to understand the game rules.

What’s Next

We can use the same rock paper scissors python code to simulate this game by adding two new actions, lizard and spoke, without needing to modify functions get_user_action() and get_program_action(). However, it will be hard to fit every case to determine the winner. Before jumping to the solution, let us see a way we can make the function determine_winner() more readable. Instead of writing all the cases, we can use python dictionaries to determine the winner. Let us see how:

Here, we store the game possibilities in key-pair data structure dictionaries. We use values for each key as the Actions that get defeated for their corresponding keys. For example, Rocks (key) beats Scissors (value). This way, instead of comparing each case using if...elif...else, we simplified the logic, which will help to expand the program for more actions.

Now that we have simplified the logic to add two more actions, lizard and spoke. Let us see the code for the game rock paper scissors lizard and spoke.

Notice, in the above implementation, there are mainly two significant changes:

  1. We added two more actions in our Action class: lizard and spoke.
  2. We modified our determine_winner() function to determine the winner of the game. This change mainly involves changing the victories dictionary to include two more actions: lizard and spoke.

This is it! We have completed the code. Have an excellent game.

Conclusion

  • Taking and displaying output in the console using Python to play the rock paper scissors game.
  • Using while loops to create infinite recurring conditions in the Rock paper scissors python program.
  • Cleaning up the code logic using Enums and functions.
  • Using dictionaries in Python to simplify more complex rules.