top of page
Search

Step 5: Let's build a game!

  • Writer: Coding GP Team Project
    Coding GP Team Project
  • Oct 14, 2020
  • 2 min read

Updated: Nov 18, 2020



This is the moment that you have been waiting for! So let's build the popular game: rock, paper, scissor, in Python !


First we are going to import a module, called random. This allows the computer to randomly pick digits for our program.

import random

Then we shall take input from the user, define the three possibilities (rock, paper or scissors) and let the computer randomly choose one of the options. We shall use lists when we need to have multiple data values in one variable.

user = input("Please Enter  rock, paper, or scissors: ")
options = ['rock', 'paper', 'scissors']
computer = random.choice(options)

Then we shall print out the results that we obtained:

print("You chose:",user)
print("The computer chose:",computer)
user = user.lower()

Now we shall check for all possible conditions, in which a user can lose or win, using if-else loops, and check if the user input is a valid option:

if user == computer:
  print ("It was a draw")
elif user == 'paper':
  if computer == 'rock':
    print ("You Win!")
  else:
    print ("You lose!")
elif user == 'rock':
  if computer == 'scissors':
    print ("You win!")
  else:
    print ("You lose!")
elif user == "scissors":
  if computer == 'rock':
    print ("You Win!")
  else:
    print ("You lose!")
else:
  print ("Not a valid option")

And there is it, we just created a game in Python in just 30 lines! The complete source code for this game is:

#importing random module
import random
#Defining variables
user = input("Please Enter  rock, paper, or scissors: ")
options = ['rock', 'paper', 'scissors']
computer = random.choice(options)
#Printing them for the user to see
print("You chose:",user)
print("The computer chose:",computer)
user = user.lower()
#Checking all conditions
if user == computer:
  print ("It was a draw")
elif user == 'paper':
  if computer == 'rock':
    print ("You Win!")
  else:
    print ("You lose!")
elif user == 'rock':
  if computer == 'scissors':
    print ("You win!")
  else:
    print ("You lose!")
elif user == "scissors":
  if computer == 'rock':
    print ("You Win!")
  else:
    print ("You lose!")
else:
  print ("Not a valid option")

You can try out the game here:



In 5 Steps, you were able to develop a game in Python!


Congratulations !


 
 
 

Comments


©2020 by Code2Learn

bottom of page