DEV Community

Cover image for Rock, Paper, Scissors Python Beginner Game
codingstreets
codingstreets

Posted on

Rock, Paper, Scissors Python Beginner Game

Summary: Rock, Paper, Scissors

In this comprehensive guide, you'll learn how to build a classic Rock, Paper, Scissors game in Python where players can compete against the computer.

We'll walk through creating an interactive console application that handles user input, generates computer choices randomly, implements game logic to determine winners, and provides a seamless gaming experience with proper error handling.

You'll understand how to use Python's random module, work with lists, implement conditional statements, and create infinite loops for continuous gameplay - all fundamental concepts for beginner to intermediate Python programmers.

WATCH VIDEO: How to Create Rock, Paper, Scissors in Python — Beginner Programming Project

Complete Code: Build a Rock Paper Scissors Game in Python

#Logic Building
#1. display options [Rock, Paper, Scissors]
#2. 2 players - Person & Computer
#3. choose option & display
#4. condition - win or loose

import random
def game():

    #game options
    options = ["Rock", "Paper", "Scissors"]

    while True:
        #how to start - game guide
        print("Game Start!!!!")
        print("1. Rock")
        print("2. Paper")
        print("3. Scissors")
        print("4. Exit\n")

        #ask user's number to start game 
        ask_user = int(input("Choose a number from 1 to 4: "))

        #check if user'number is out of range - 1 to 4.
        if ask_user not in range(1,5):
            print(ask_user," is out of range. Choose a number from 1 to 4.\n")
            continue

        #exit from game
        if ask_user == 4:
            print("Thanks for playing.")
            break

        #get user option from list
        user_option = options[ask_user-1]
        print("User:", user_option)

        #get computer option from list
        computer_index_number =  random.randint(0,2)
        computer_option = options[computer_index_number]
        print("Computer:", computer_option,"\n")

        #condition if both options are same
        if user_option == computer_option:
            print("Got same option! Game Tie...\n")
            continue

        #conditions for User Winning 
        if (user_option == "Rock") and (computer_option == "Scissors"):
            print("User Won!!!",user_option, "beats", computer_option,"\n")
        elif (user_option == "Paper") and (computer_option == "Rock"):
            print("User Won!!!",user_option, "beats", computer_option,"\n")
        elif (user_option == "Scissors") and (computer_option == "Paper"):
            print("User Won!!!",user_option, "beats", computer_option,"\n")

        #conditions for Computer Winning
        else:
            print("Computer Won!!!",computer_option, "beats", user_option,"\n")

game()
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Code Explanation

Let’s break down this Rock, Paper, Scissors implementation into understandable components.

1. Importing Required Modules and Function Definition

import random

def game():
Enter fullscreen mode Exit fullscreen mode

import random: This imports Python's built-in random module, which we'll use to generate the computer's random choices.

def game():: We define a main function called game() that encapsulates all our game logic, making the code organized and reusable.

2. Game Setup and Options

    options = ["Rock", "Paper", "Scissors"]
Enter fullscreen mode Exit fullscreen mode

options list: This list stores the three possible game choices. Using a list makes it easy to access options by index and keeps our code clean.

3. Main Game Loop

    while True:
        print("Game Start!!!!")
        print("1. Rock")
        print("2. Paper")
        print("3. Scissors")
        print("4. Exit\n")
Enter fullscreen mode Exit fullscreen mode

while True:: Creates an infinite loop that keeps the game running until the player chooses to exit.

Game Menu: The print statements display a clear menu showing all available options with corresponding numbers for easy selection.

4. User Input Handling

        ask_user = int(input("Choose a number from 1 to 4: "))

        if ask_user not in range(1,5):
            print(ask_user," is out of range. Choose a number from 1 to 4.\n")
            continue
Enter fullscreen mode Exit fullscreen mode

User Input: input() captures the user's choice, and int() converts it to an integer for numerical comparison.

Input Validation: The if ask_user not in range(1,5) check ensures the input is between 1-4. If invalid, it displays an error message and continue restarts the loop.

5. Exit Mechanism

        if ask_user == 4:
            print("Thanks for playing.")
            break
Enter fullscreen mode Exit fullscreen mode

Exit Condition: When user selects 4, a thank you message is displayed and break terminates the while loop, ending the game.

6. Player and Computer Choice Generation

        user_option = options[ask_user-1]
        print("User:", user_option)

        computer_index_number = random.randint(0,2)
        computer_option = options[computer_index_number]
        print("Computer:", computer_option,"\n")
Enter fullscreen mode Exit fullscreen mode

User Choice: options[ask_user-1] converts the user's number (1-3) to the corresponding list index (0-2) and retrieves the option.

Computer Choice: random.randint(0,2) generates a random number between 0-2, which serves as the index for the computer's selection.

7. Game Logic and Winner Determination

        if user_option == computer_option:
            print("Got same option! Game Tie...\n")
            continue

        if (user_option == "Rock") and (computer_option == "Scissors"):
            print("User Won!!!",user_option, "beats", computer_option,"\n")
        elif (user_option == "Paper") and (computer_option == "Rock"):
            print("User Won!!!",user_option, "beats", computer_option,"\n")
        elif (user_option == "Scissors") and (computer_option == "Paper"):
            print("User Won!!!",user_option, "beats", computer_option,"\n")
        else:
            print("Computer Won!!!",computer_option, "beats", user_option,"\n")
Enter fullscreen mode Exit fullscreen mode

Tie Condition: First check if both choices are identical - if so, declare a tie and restart the game.

User Win Conditions: Three specific conditions where the user wins according to Rock, Paper, Scissors rules:

  1. Rock beats Scissors
  2. Paper beats Rock
  3. Scissors beats Paper

Computer Win: If it's not a tie and user doesn't win, computer automatically wins (the else case).

8. Game Initialization

game()
Enter fullscreen mode Exit fullscreen mode

This function call starts the game when the script is executed.

Now it’s Your Turn!

Let’s open your VS code and write the code. Let’s see how it worked for you! Drop a comment with your win/loss ratio after 10 games. Also, here’s a task for you: Try to add a score counter to the game and let’s see how many times you won the game with the computer. Don’t forget to write in the YouTube Video comment section because the first response I’ll do pin and like too.

Conclusion: Rock Paper Scissors Game in Python

This Rock, Paper, Scissors implementation demonstrates several fundamental programming concepts in an engaging, practical project. You've seen how to handle user input with validation, generate random computer choices, implement complex game logic using conditional statements, and create an interactive loop for continuous gameplay.

The code structure is clean and modular, making it easy to extend with features like score tracking, multiple rounds, or even different game modes. This project serves as an excellent foundation for understanding how to build interactive applications in Python and can be expanded into more complex games or utilities.

EXPLORE MORE PYTHON BEGINNER PROJECTS

codingstreets - YouTube

Whether you're a beginner just starting or looking to sharpen your skills, this channel is your go-to resource for Python. From Python Tutorial to various beginner-friendly python projects, Python tips and tricks, and quick Python Shorts that deliver bite-sized tutorials in under a minute, you will find advanced insights to take your coding to the next level. 🔔Subscribe now, 🔔and let's start coding together --- A Path Towards Coding I don't know how long this journey will run, but I know that this journey will bring us joy if at least one of you joins us in this journey and build a community to learn together! Have fun! 🎈

favicon youtube.com

Top comments (0)