What will we cover?
How to use Randomness in Python and create a Rock-Scissor-Paper game.
Step 1: Randomness in Python
To make games interesting you need some unpredictable aspects. This is where randomness is used.
Luckily, Python has a library to make randomness. To simulate rolling a die can be done as follows.
import random die = random.randint(1, 6) print(die)
Where randint(1, 6) returns a random integer from 1 to 6, both inclusive.
Step 2: The Rock-Scissor-Paper game
I think most know the game. If not, read the rules on wiki.
Let’s try a game of it.
print("Enter choice \n 1. Rock \n 2. Paper \n 3. Scissor \n") choice = int(input("Choice: ")) computer_choice = random.randint(1, 3) if choice == computer_choice: print("Draw") elif choice == 1: if computer_choice == 2: print("Computer wins, Paper") else: print("You win, Scissor") elif choice == 2: if computer_choice == 1: print("You win, Rock") else: print("Computer wins, Scissor") elif choice == 3: if computer_choice == 1: print("Computer wins, Rock") else: print("You win, Paper")
Step 3: What is Next?
I am happy you asked.
If this is something you like and you want to get started with Python, then this is part of a 8 hours FREE video course with full explanations, projects on each levels, and guided solutions.
The course is structured with the following resources to improve your learning experience.
- 17 video lessons teaching you everything you need to know to get started with Python.
- 34 Jupyter Notebooks with lesson code and projects.
- A FREE 70+ pages eBook with all the learnings from the lessons.
See the full FREE course page here.