We're going to dive headfirst into creating your very first Python game: Rock, Paper, Scissors.
Let's Get Started:
Open your Python IDLE and create a new file named rps.py
. Now, let's start coding:
from random import randint
# Create a list of play options
t = ["Rock", "Paper", "Scissors"]
# Assign a random play to the computer
computer = t[randint(0,2)]
# Set player to False
player = False
# Game Loop
while player == False:
# Set player to True
player = input("Rock, Paper, Scissors?")
# Check for a tie
if player == computer:
print("It's a tie!")
# Check for player winning scenarios
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
else:
print("You win!", player, "smashes", computer)
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
else:
print("You win!", player, "covers", computer)
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
else:
print("You win!", player, "cut", computer)
# Handle invalid inputs
else:
print("That's not a valid play. Check your spelling!")
# Reset player status to continue the loop
player = False
computer = t[randint(0,2)]
Understanding the Code:
Let's dissect what's happening in our code:
We import
randint
from therandom
module to generate random integers, which we'll use to determine the computer's play.We create a list,
t
, containing the play options: "Rock", "Paper", and "Scissors".The computer's play is randomly selected from the list.
We set the initial state of the player to
False
to indicate that they haven't made a play yet.The game loop (
while
loop) runs until the player makes a valid play.Inside the loop, we prompt the player for their choice using the
input()
function.Based on the player's input, we compare it with the computer's play to determine the outcome of the game.
We handle different scenarios such as a tie, player wins, or invalid inputs.
Finally, we reset the player status to
False
to continue the loop and generate a new play for the computer.
Top comments (0)