Rock, Paper, Scissors in Python

Implementing Rock, Paper, Scissors in Python

Oliver Lövström
Internet of Technology
2 min readJan 25, 2024

--

Welcome to the third day of my 30-day Python coding challenge. Today, we’re developing a simple but classic game: rock, paper, scissors.

Photo by Fadilah Im on Unsplash

Like our previous ones, this challenge is inspired by various beginner Python projects. You can find more details here:

I have decided to use some ASCII art to make it a bit more interesting. Credits go to wynand1004 on GitHub for the ASCII art used in this project. Check out their work here.

We start by establishing the user’s options:

CHOICES = {
"rock": 1,
"paper": 2,
"scissors": 3,
"r": 1,
"p": 2,
"s": 3,
"1": 1,
"2": 2,
"3": 3,
}

Then, we implement the game loop. Here, players make a choice, which is compared against the computer’s random selection:

print("Welcome to Rock, Paper, Scissors!")

while True:
computer_choice = random.randint(1, 3)
user_choice = input("Choose Rock, Paper, or Scissors: ").strip().lower()

if user_choice not in CHOICES:
print("Invalid input.")
continue

user_choice = CHOICES[user_choice]

print("You chose")
render_choice(user_choice)

print("\nComputer chose")
render_choice(computer_choice, render_time=1)

if user_choice == computer_choice:
print("It's a tie!")
elif (
(user_choice == 1 and computer_choice == 3)
or (user_choice == 2 and computer_choice == 1)
or (user_choice == 3 and computer_choice == 2)
):
print("You win!")
else:
print("Computer wins!\n")

play_again = input("Play again? (yes/no): ").strip().lower()
if play_again != "yes":
break

To make the game a tad bit more exciting, I’ve added a render_choice function that slowly renders each icon.

The computer’s choice is revealed gradually, heightening the suspense:

def render_choice(choice: int, render_time: float = 0) -> None:
"""Render choice.

:param choice: Integer representing the choice.
:param render_time: Float representing the time to render the icon.
"""
for line in ICON[choice]:
print(line)
time.sleep(render_time / len(ICON[choice]))

Launching the game:

Rock, paper, scissors in the terminal

When you run the program, you are greeted with a visual representation of your choice, followed by the computer’s slowly generated choice, making the game come to life. All the code for these projects is available on Python Projects on GitHub.

Further Reading

If you want to learn more about programming and, specifically, Python and Java, see the following course:

Note: If you use my links to order, I’ll get a small kickback. So, if you’re inclined to order anything, feel free to click above.

--

--