If you're looking for a fun and easy way to practice your Python programming skills, building a simple Rock, Paper, Scissors game is a great project. This game allows users to interact with the program and make decisions, while also providing a random element through the computer's choices.
In this tutorial, we'll walk you through how to create a Rock, Paper, Scissors game in Python. You will learn how to implement user input, random selection, and game rules with a few lines of code.
Rock, Paper, Scissors Game Overview
The game is simple:
-
The user chooses one of three options: rock, paper, or scissors.
-
The computer randomly picks one of these choices.
-
The winner is determined based on the following rules:
-
Rock beats Scissors.
-
Scissors beats Paper.
-
Paper beats Rock.
-
If both the user and the computer select the same option, it's a tie.
Code Explanation
import random choices = ["rock", "paper", "scissors"] print("Rock, Paper, Scissors Game ✊✋✌️") while True: user = input("Choose rock, paper or scissors (or 'quit' to stop): ").lower() if user == 'quit': print("Thanks for playing!") break if user not in choices: print("Invalid choice. Try again!") continue computer = random.choice(choices) print("Computer chose:", computer) if user == computer: print("It's a tie!") elif (user == "rock" and computer == "scissors") or \ (user == "paper" and computer == "rock") or \ (user == "scissors" and computer == "paper"): print("You win!") else: print("You lose!")
Here's the Python code for the Rock, Paper, Scissors game:
Breaking Down the Code
-
Importing the Random Module
-
We begin by importing Python's random module. This will allow the computer to randomly choose between rock, paper, and scissors.
-
-
User Interaction
-
The game continuously prompts the user to input their choice until they type "quit". We use the input() function to get the user’s input and convert it to lowercase to avoid case-sensitive issues.
-
-
Computer's Random Choice
-
The computer's choice is randomly selected from the choices list using random.choice(). This ensures that the game is unpredictable and fun.
-
-
Game Logic
-
The game compares the user's choice with the computer’s:
-
If both choices are the same, it’s a tie.
-
If the user’s choice beats the computer’s (e.g., rock beats scissors), the user wins.
-
Otherwise, the computer wins.
-
-
-
Looping Until the User Wants to Stop
-
The while True  loop ensures that the game continues until the user types "quit".
-