in Games

Rock, Paper, Scissors with Python

python-operators-and-conditions-games

In this article we will discuss Python Operators and Conditions, their syntax and different ways to use them in order to achieve the same result: a game of Rock, Paper, Scissors. To accomplish this we will focus on the following concepts:

  • Operators
  • Conditional Statements

Python Operators

Operators are symbols or statements that manipulate  the value of the operands.

Consider the following example: 10 * 3 = 5.

The integers  ’ 10 ’ and ‘ 3 ’ are operands (which are also referred to as variables), while  ‘ *  ’ is the operator that performs the action of multiplication. It’s important to understand that the use of these operators are not solely limited to operations like addition or multiplication. Some operators can be used for comparisons or to confirm whether a statement is ‘true’ or ‘false’.

For example, in the previous paragraph I wrote “The integers ‘ 10  ’ and  ‘ 3 ’ are operands…”. In this example the word ‘  and  ’ just became the operator since it compared the two integers. We will be making use of the Logical Operators in one of our games.

The Python language supports the following Operators:

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Identity Operators
  • Membership Operators
  • Bitwise Operators

For examples and in-depth details on these operators, Programiz  is an excellent resource that I recommend checking out.

Python Conditional Statements

 Conditional Statements, also referred to as If…else statements are used to control the flow of an operation. In order to accomplish this we make use of the Boolean values ‘true’ and ‘false’. If a statement is ‘true’ then do this, otherwise do this.

To illustrate this let’s start with our basic game of rock paper scissors.

We’ll begin by defining a function ‘basicRPS’ that will take two arguments, player Ones hand (p1) and player Twos hand (p2). Once we’ve got the basics down we’ll add a little logic to our game so that we can play against the computer.

def basicRPS(p1,p2):

Our first step is to identify and comment the rules of our game.

#ROCK BLUNTS SCISSORS
#SCISSORS CUTS PAPER
#PAPER COVERS ROCK
#IF PLAYERS CHOOSE THE SAME HAND THEN IT'S DRAW

From our description we know that there are 3 Options that both users can choose from: Rock, Paper or Scissors. Depending on each players choice we will receive a winner. Now if both users play the same hand then the result is a draw. Since resulting in a draw cancels out the operation lets use this as our first condition.

if p1.title() == p2.title():
    return 'Draw!'

Assignment and Comparison Operators

You’re probably thinking ”Wait a minute, why are there two ‘ = ’ signs?” Well I’m glad you asked. In Python ‘ = ’ is considered an Assignment Operator while ‘ == ’ is considered a Comparison Operator.

Assignment Operators are used to assign and reassign the value of a given variable. For example:

a = 5
5
a = 2
a
2

We started off by assigning the value of ‘5’ to the variable ‘a’ and then assigned the value of ‘2’ to the same variable.

Comparison operators tell us if a statement is true or false. Consider the following:

a = 5
b = 5
c = 3
a == b
True
a == c
False

In this example we assigned the value  ‘5’ to both ‘a’ and ‘b’. Then we asked is ‘a’ Equaled to ‘b’? To which the program returned true. Before moving on let’s look at one more example.

a = 5
b = '5'
a == b
False

You’re probably thinking “If a and b are both 5 why did Python return false?” Well it’s simple really, when we assign a value, we also assign the type of value. Take a look.

type(a)
class'int'
type(b)
class'str'

 When the comparison operator asks is ‘a’ Equaled to ‘b’, it’s really asking is ‘a’ really the same type and value as ‘b’? By surrounding the Number 5 with quotation marks I assigned the type of value to string resulting in false.

With that being said lets get back to our game.

if p1.title() == p2.title():
    return 'Draw!'

We asked is Player1’s hand Equaled to Player2’s hand. We add the ‘.title()’ method to account for caps. If the result is true we return ‘Draw’. If false the program continues to run. Now we need to decide what happens if both players make unique calls. We’ll accomplish this using the ‘elif’ statement.

# If the player chooses rock
elif p1.title() == 'Rock' and p2.title() == 'Paper':
    return 'Player 2 won!'

elif p1.title() == 'Rock' and p2.title() == 'Scissors':
    return 'Player 1 won!

Adding our logic we decide, If player1 chooses rock ‘and’ player2 chooses paper then player2 wins. By using the ‘elif’ statement, we tell Python that if the last statement returned false then run this. In Python the ‘and’ operator is called a Logical Operator. In order for the program to return true both statements must be true. If either one is false then the program will return false. From this point we’ll go ahead and using the same logic decide what happens in the event the user chooses paper and scissors.

#If the user chooses paper
elif p1.title() == 'Paper' and p2.title() == 'Rock':
    return 'Player 1 won!

elif p1.title() == 'Paper' and p2.title() == 'Scissors':
    return 'Player 2 won!'

# If the user chooses scissors
elif p1.title() == 'Scissors' and p2.title() == 'Paper':
    return 'Player 1 won!'

elif p1.title() == 'Scissors' and p2.title() == 'Rock':
    return 'Player 2 won!'

There you have it! A basic game of Rock, Paper, Scissors. At this point we have a pretty good understanding for the logic involved. Let’s take it a step further and adjust our code so that we can play against the computer.

Python Rock, Paper, Scissors

In order for us to play against the computer and have a fair game we’ll need to import choice from the random module.

from random import choice

The choice model allows us to import a random element from a given list. In our case the list will be one of our three options. Before we implement our logic lets define our function and assign our variables.

def playRPS():
    beats = {'rock' : 'scissors', 'scissors' : 'paper','paper': 'rock'}
    computerHand = beats[choice(['rock','paper','scissors'])]
    playerHand = input('Choose Rock, Paper, Scissors: '

First we created a dictionary called beats with a key value pair of outcomes (Key beats Value). Using the same dictionary we call the choice method on a list of hands that are ‘Equaled’ to the keys in the beats dictionary. Our last variable ‘playerHand’ assigns the user input as its value.

As a result , of  this basic set up we can implement our logic.

    if beats[playerHand] == computerHand:
        print(f'Computer played {computerHand}')
        return 'Player Wins!'

This may or may not take you a few passes to make sense of.  Lets quickly work our way through this one just in case.

Lets say that the player inputs ‘rock’

The value for the key ‘rock’ is scissors

If the computer randomly chooses ‘scissors’ then Player Wins because rock beats scissors. Easy enough right? Now we just need to add the elif statement in the event that the computer wins.

    elif beats[computerHand] == playerHand:
        print(f'Computer played {computerHand}')
        return 'Sorry, Computer Won...'

Just like before if the value for the key(computers hand) is the same as the players hand then the computer wins. Now our last step is to account for a draw.

return 'Draw!'

This step is basically says that if none of the other two statements are true then return ‘draw’. An there you have it! You just programmed an interactive game of rock, paper, scissors.

Conclusion

To recap, we learned that there are many types of Python Operators and Conditional Statements.  We also learned that conditional statements can be used to control the flow of an operation.As a tool conditional statements are priceless and should be in every programmers toolkit. We made a basic game of Rock, Paper, Scissors and even stepped it up a notch so that we could play against the computer.

If you enjoyed this article and want to see other projects just like it in the future please leave a comment below. Until next time!

Share:

PyTechDrae

Leave A Comment

Your email address will not be published. Required fields are marked *