Learn Python by Making Stone paper Scissor game

Posted by ArunShaji on 18-Sep-2021

Hello there,

Today, we’ll head jump into the world of Python by creating a computer version of the classical game: Stone paper scissors.

So, without any delay, let’s jump into code :) 

Installation of Python 3

Follow these links

for windows : https://docs.python.org/3/using/windows.html

For Unix: https://docs.python.org/3/using/unix.html

For Mac: https://docs.python.org/3/using/mac.html

Problem statement and approach

  • This game is played between a human player and the CPU. 
  • The user can choose any of the Stone, Paper, and Scissors, and the CPU will choose with any random choice from these options. 
  • In each round, there are two outcomes, either one player wins or a tie.
  • The basic rule for the win is “Stone crushes scissors” or “Paper covers stone” or “Scissors cut paper”. Otherwise a draw.
  • The game is continued until any of the user or CPU scores 5. 

Concepts to be Covered: 

  • Accepting and displaying information in the terminal
  • Basic data structures - Lists, & Dictionaries
  • Basic Control structures

Link To Repository

The whole code for this tutorial can be accessed here: https://github.com/afsal-parseltongue/stone-paper-scissors/blob/master/game.py

How to run the code

Once you’ve cloned or downloaded the file, and if you have python ready on your machine, you can run the script using:

python game.py

Code

import Keyword

import random

The first line starts with an import statement. “import” is a Python keyword used to load another module to our code. It can be a built-in module or a user-defined module. The syntax for valid import statement are:

import <module_name>

from <module_name> import <submodule/function/class/variable>

 from module.submodule import <function/variable>

In our code, we import the built-in random module, random, which has a lot of methods related to pseudo-random numbers. But we only need random.choices() for this tutorial. 

The print() function   

print("\nWelcome to stone paper scissor game")

print() is a method that is built into Python, meaning you don’t need to import this method. print() accepts one or more string values and displays them to the user. The `\n` is an escape character that moves the cursor to the next line, forcing it to print the text in a new line.

The input() function

name = input("\nPlease enter your name: ")

We need to accept the user’s name. For reading inputs from the user we use another built-in method - “input()”. This method accepts a string, reads a line from the standard input (keyboard), and returns that value in the “str” (string) data type. The first argument to this method is shown as the prompt for the user to type in. So, we read the user’s name and store it in the variable “name”

list

valid_entries = ['st', 'pa', 'sc']

A list is a collection of data, unlike arrays, a list can store mixed-type data. Here, we declare a list with the strings 'st', 'pa', 'sc' which corresponds to Stone, Paper & Scissors. This list will be used to validate whether the user had entered the proper choice.

dictionary

choice_name_map = {

    "st": "Stone",

    "pa": "Paper",

    "sc": "Scissor"

}

dictionary is also another Python’s data type, which stores the data in the key-value form. The syntax for defining a dictionary (dict)

<name of variable> = {
    <key1>: <value1>,
    …
}

And the values of the dictionary are accessed via the keys. For example, to get the value of “key1” can be accessed using

 dict_name["key1"]

 So, in our code, we declare a dictionary that stores the choices and their abbreviations.

 function

 The main logic of our Stone, Paper, Scissors is written inside a method. A function is a named block of instructions, that can be called from other parts of the program. We use def keywork for defining functions

In Python, we will not see any curly brackets to separate a block, instead, we use indentation for code blocks. Usually, we use 4 spaces for indenting the code. Mixing of tabs and spaces together for indentation is not allowed.

 The syntax for method definition is:

 

def method_name(argument 1, argument 2, …):
    <method definition>

 As Python is a dynamically typed language, we’ll not specify the argument type or return types. Also, zero or more arguments can be passed, zero or more arguments can be returned. In Python, methods are first-class objects, meaning you can assign them to a variable and can be used like any variable. Methods are a topic for another post, for now, we’ll stop here.

The while loop

The while loop is an important control structure in Python, which is used to execute a block of code repeatedly as long as a particular condition is satisfied. The general syntax for the while loop is:

while condition:
    <block of statements>

In our game, there are two while loops are used. One has True as the control condition is an infinite loop, which never ends unless some control statement is used to break from the loop. 

The reason, why we use an infinite loop, is that we should continue the game as long as the user wishes to play.

 in operator

The Python keyword in is a special and very useful operator.  in keyword is used for checking an item contained in the list. For example, we have the following map:

 valid_entries = ['st', 'pa', 'sc']

 If we want to check whether the user entered any of the valid choices, we use:

entry in valid_entries

in returns True, if entry is found in the list, otherwise False.

 Logical Operators

Python provides three logical operators to evaluate boolean expressions:

  • and -> Takes the form X and Y and returns True if both X and Y are True, otherwise False is returned.
  • or -> Takes the form X or Y and returns True either/both X or Y is True. Returns False, if both X and Y are False.
  • not -> Used to negate an expression: not X returns True, if X is False. If X is True, False is returned.

 The logical operators are mainly used to control the flow of the code. They make the code more readable.

 The if-elif-else control structure

if-else statements are central to any programing language. They choose the execution flow. Unlike other programming languages, Python uses the keyword elif for else if. The syntax for  this control statement is:

if condition1:
    <statement block 1>
elif condition 2:
    <statement block 2>

…

elif condition n:
    <statement block n>
else:
    <default block>

 The execution flow is that if conditions are matched in the order they were written, and if any condition is evaluated to True, the indented block following that will be followed. If none of the conditions are matched, else block will be executed. else block is purely optional, without else, it should work.

 Enclosing the condition in parentheses ( ) is not mandatory, unlike C or C++. Only use brackets, if you need to change the order of evaluation of conditions. Also, the colon (:) after the condition is mandatory. Indentation (white spaces/tabs) are used to mark a code block.

 The break statement

As I mentioned before, there is an infinite while loop in Line 17. We need some way to break from the game if the users wish to do so. For this, we use another built-in statement called break. When the Python interpreter sees this keyword, it immediately jumps out of the loop, and the statements after the loop body will be executed next.

The built-in variable: __name__

When the Python interpreter runs the code, it sets some of the special variables, which we can access from the code. They will start with a double underscore (__) and end with the same. __name__ is set to the name of the module which is being executed. If we run our stone paper scissors game from the terminal using:

python game.py 

then, the interpreter will set the __name__ to the string ‘__main__’. Otherwise, if we import this file to some other python program, it will be set to the module name ‘game’.

Thus it can be used to distinguish whether the script is running stand-alone or not.

 So, that’s it for the day, we’ll look into more on the following tutorials. Don’t forget to subscribe!