User plays Rock, Paper, Scissors against the computer. Game repeats until user quits or a score target is hit. Tracks score, validates input, and gives feedback.
# ๐ Import random module to let computer randomly choose an option
import random
# ๐ฏ Define valid choices in a list
choices = ["rock", "paper", "scissors"]
# ๐ง Score trackers
user_score = 0
comp_score = 0
# ๐ Function to decide the winner of a round
def decide_winner(user, comp):
"""
Takes user and computer choice, returns outcome string:
'win', 'lose', or 'draw'
"""
if user == comp:
return "draw"
# Define winning conditions
if (user == "rock" and comp == "scissors") or \\
(user == "paper" and comp == "rock") or \\
(user == "scissors" and comp == "paper"):
return "win"
return "lose"
# ๐ Main game loop
while True:
print("\\n--- Rock, Paper, Scissors Game ---")
print("Enter your choice (rock/paper/scissors) or 'q' to quit:")
user_choice = input("๐ Your move: ").lower().strip()
# ๐ Check for quit
if user_choice == "q":
print("๐ Thanks for playing!")
break
# โ Invalid input handling
if user_choice not in choices:
print("โ ๏ธ Invalid input. Please enter rock, paper or scissors.")
continue
# ๐ป Computer makes a random choice
comp_choice = random.choice(choices)
print(f"๐ค Computer chose: {comp_choice}")
# ๐ Decide winner and update scores
result = decide_winner(user_choice, comp_choice)
if result == "win":
print("โ
You win this round!")
user_score += 1
elif result == "lose":
print("โ You lost this round.")
comp_score += 1
else:
print("๐ค It's a draw!")
# ๐งพ Display current score
print(f"๐ Score -> You: {user_score} | Computer: {comp_score}")
Feature | Concept Used | Level |
---|---|---|
Track history of moves | Lists | Easy |
Add round number | Loops & Counters | Easy |
Play up to N rounds | Loop + Break Conditions | Medium |
Create a score file (score.txt ) |
File Handling | Medium |
Add emojis using Unicode | Fun UX | Easy |
GUI version (Tkinter) | Python Module | Medium |
Function to replay game | Function Composition | Medium |
Use main() structure |
Good Coding Practice | Medium |
Use *args or **kwargs to handle optional input |
Chapter 8 | Medium |