Let's dive into the classic game of Rock Paper Scissors, specifically how to implement it using CodeHS and Python. We'll break down the code step-by-step, making it easy to follow along even if you're a beginner. This seemingly simple game provides an excellent foundation for understanding fundamental programming concepts like conditional statements, user input, random number generation, and loops. This guide covers the basics, expands to include features like user input validation and scoring, and even explores potential areas for further enhancement Practical, not theoretical..
Understanding the Core Logic of Rock Paper Scissors
The game Rock Paper Scissors is built on a simple set of rules:
- Rock crushes Scissors.
- Scissors cuts Paper.
- Paper covers Rock.
If both players choose the same gesture, it's a tie. To translate these rules into code, we need to represent each gesture (Rock, Paper, Scissors) with a specific value (e.g., a string or an integer) and then implement the logic to determine the winner based on the choices made by the computer and the player No workaround needed..
Setting Up the Basic Code Structure in CodeHS
First, let's set up the basic structure in CodeHS using Python. Also, we need to import the random module to allow the computer to make random choices. We'll define the possible choices (Rock, Paper, Scissors) and write the main game loop Which is the point..
import random
def main():
choices = ["rock", "paper", "scissors"]
computer_choice = random.choice(choices)
player_choice = input("Enter your choice (rock, paper, scissors): ").lower()
print("Computer chose:", computer_choice)
print("You chose:", player_choice)
# Determine the winner (implementation will come later)
if __name__ == "__main__":
main()
This code sets up the following:
- Importing the
randommodule: This line allows us to use functions from therandommodule, especiallyrandom.choice(), which will be used to randomly select the computer's choice. - Defining the
main()function: This is where the core logic of the game will reside. It's a good practice to encapsulate your code within functions for better organization. - Creating a list of choices: The
choiceslist holds the possible options for the game: "rock", "paper", and "scissors". - Generating the computer's choice:
random.choice(choices)selects a random element from thechoiceslist and assigns it to thecomputer_choicevariable. - Getting the player's choice:
input()prompts the player to enter their choice..lower()converts the input to lowercase, making it case-insensitive. - Printing the choices: This provides immediate feedback to the player, showing what both they and the computer chose.
- Calling the
main()function: Theif __name__ == "__main__":block ensures that themain()function is executed when the script is run.
Implementing the Winning Logic
Now, let's implement the core logic to determine the winner. Which means we need to compare the player's choice with the computer's choice and apply the rules of the game. This involves using if, elif, and else statements.
import random
def main():
choices = ["rock", "paper", "scissors"]
computer_choice = random.choice(choices)
player_choice = input("Enter your choice (rock, paper, scissors): ").lower()
print("Computer chose:", computer_choice)
print("You chose:", player_choice)
if player_choice == computer_choice:
print("It's a tie!")
else:
print("Invalid choice. You win!You lose.")
elif player_choice == "paper":
if computer_choice == "rock":
print("Paper covers rock! ")
else:
print("Scissors cuts paper! You win!")
else:
print("Paper covers rock! That said, ")
elif player_choice == "rock":
if computer_choice == "scissors":
print("Rock crushes scissors! You lose.")
else:
print("Rock crushes scissors! ")
elif player_choice == "scissors":
if computer_choice == "paper":
print("Scissors cuts paper! Practically speaking, you win! Also, you lose. Please enter rock, paper, or scissors.
if __name__ == "__main__":
main()
Here's a breakdown of the added logic:
- Tie Condition:
if player_choice == computer_choice:checks if both choices are the same. If they are, it prints "It's a tie!". - Player Chooses Rock:
elif player_choice == "rock":handles the case where the player chooses rock. It then checks the computer's choice:- If the computer chose scissors, the player wins ("Rock crushes scissors! You win!").
- Otherwise (the computer chose paper), the player loses ("Paper covers rock! You lose.").
- Player Chooses Paper:
elif player_choice == "paper":handles the case where the player chooses paper, with similar logic. - Player Chooses Scissors:
elif player_choice == "scissors":handles the case where the player chooses scissors, with similar logic. - Invalid Choice:
else:handles the case where the player enters an invalid choice (anything other than "rock", "paper", or "scissors"). It prints an error message ("Invalid choice. Please enter rock, paper, or scissors.").
Adding a Game Loop
To allow the player to play multiple rounds without restarting the program, we can add a while loop. We'll also add a condition to allow the player to quit the game.
import random
def main():
choices = ["rock", "paper", "scissors"]
playing = True
while playing:
computer_choice = random.choice(choices)
player_choice = input("Enter your choice (rock, paper, scissors, or 'quit' to exit): ").lower()
if player_choice == "quit":
playing = False
print("Thanks for playing!")
break # Exit the loop immediately
print("Computer chose:", computer_choice)
print("You chose:", player_choice)
if player_choice == computer_choice:
print("It's a tie!")
elif player_choice == "rock":
if computer_choice == "scissors":
print("Rock crushes scissors! Which means you win! ")
else:
print("Paper covers rock! Which means you lose. ")
elif player_choice == "paper":
if computer_choice == "rock":
print("Paper covers rock! You win!Consider this: ")
else:
print("Scissors cuts paper! Think about it: you lose. Day to day, ")
elif player_choice == "scissors":
if computer_choice == "paper":
print("Scissors cuts paper! And you win! ")
else:
print("Rock crushes scissors! Now, you lose. ")
else:
print("Invalid choice. Please enter rock, paper, or scissors.
if __name__ == "__main__":
main()
Key changes:
playingvariable: A boolean variableplayingis initialized toTrue. This variable controls the game loop.while playing:loop: The game logic is now inside awhileloop that continues as long asplayingisTrue.- Quit option: The input prompt is updated to include the option to "quit". If the player enters "quit",
playingis set toFalse, a farewell message is printed, and thebreakstatement exits the loop. This allows the player to end the game at any time.
Input Validation
Although we have basic input validation, we can improve it to handle unexpected inputs more gracefully. Also, for instance, what if the user enters a number or a special character? We can add a more solid check to ensure the input is one of the valid choices Most people skip this — try not to..
import random
def main():
choices = ["rock", "paper", "scissors"]
playing = True
while playing:
player_choice = input("Enter your choice (rock, paper, scissors, or 'quit' to exit): ").lower()
if player_choice == "quit":
playing = False
print("Thanks for playing!")
break
if player_choice not in choices:
print("Invalid choice. Please enter rock, paper, or scissors.")
continue # Go back to the beginning of the loop
computer_choice = random.choice(choices)
print("Computer chose:", computer_choice)
print("You chose:", player_choice)
if player_choice == computer_choice:
print("It's a tie!")
elif player_choice == "rock":
if computer_choice == "scissors":
print("Rock crushes scissors! You win!")
else:
print("Paper covers rock! Because of that, you lose. Even so, ")
elif player_choice == "paper":
if computer_choice == "rock":
print("Paper covers rock! On top of that, you win! Which means ")
else:
print("Scissors cuts paper! Consider this: you lose. ")
elif player_choice == "scissors":
if computer_choice == "paper":
print("Scissors cuts paper! You win!Also, ")
else:
print("Rock crushes scissors! You lose.
Worth pausing on this one.
if __name__ == "__main__":
main()
The improvement here is the if player_choice not in choices: check. This line verifies that the player_choice is actually one of the valid options in the choices list. If it's not, an error message is printed, and the continue statement jumps to the beginning of the while loop, prompting the player for input again. This prevents the rest of the code from executing with an invalid player_choice.
Adding a Scoring System
To make the game more engaging, let's add a scoring system to track the number of wins, losses, and ties.
import random
def main():
choices = ["rock", "paper", "scissors"]
playing = True
player_wins = 0
computer_wins = 0
ties = 0
while playing:
player_choice = input("Enter your choice (rock, paper, scissors, or 'quit' to exit): ").lower()
if player_choice == "quit":
playing = False
print("Thanks for playing!")
break
if player_choice not in choices:
print("Invalid choice. Please enter rock, paper, or scissors.")
continue
computer_choice = random.choice(choices)
print("Computer chose:", computer_choice)
print("You chose:", player_choice)
if player_choice == computer_choice:
print("It's a tie!")
ties += 1
elif player_choice == "rock":
if computer_choice == "scissors":
print("Rock crushes scissors! On the flip side, you win! On the flip side, ")
player_wins += 1
else:
print("Paper covers rock! You lose.")
computer_wins += 1
elif player_choice == "paper":
if computer_choice == "rock":
print("Paper covers rock! You win!")
player_wins += 1
else:
print("Scissors cuts paper! Think about it: you lose. ")
computer_wins += 1
elif player_choice == "scissors":
if computer_choice == "paper":
print("Scissors cuts paper! You win!")
player_wins += 1
else:
print("Rock crushes scissors! You lose.
print("\n--- Final Score ---")
print("Player wins:", player_wins)
print("Computer wins:", computer_wins)
print("Ties:", ties)
if __name__ == "__main__":
main()
Here's what's new:
- Score Variables: Three variables,
player_wins,computer_wins, andties, are initialized to 0 at the beginning of themain()function. These variables will store the scores. - Incrementing Scores: Inside the game loop, after each round, the appropriate score variable is incremented based on the outcome of the round. As an example, if the player wins,
player_wins += 1is executed. - Printing the Final Score: After the loop ends (when the player quits), the final score is printed to the console, showing the number of player wins, computer wins, and ties. The
\ninprint("\n--- Final Score ---")adds a newline for better formatting.
Refactoring the Code for Readability
The code is now functional, but it can be made more readable and maintainable by refactoring it into smaller, more manageable functions. We can create separate functions for getting the player's choice, determining the winner, and displaying the results Nothing fancy..
import random
def get_player_choice():
"""Gets the player's choice, validating input.That's why """
choices = ["rock", "paper", "scissors"]
while True:
player_choice = input("Enter your choice (rock, paper, scissors, or 'quit' to exit): "). Still, lower()
if player_choice == "quit":
return "quit"
if player_choice in choices:
return player_choice
else:
print("Invalid choice. Please enter rock, paper, or scissors.
def determine_winner(player_choice, computer_choice):
"""Determines the winner of the round."""
if player_choice == computer_choice:
return "tie"
elif player_choice == "rock":
if computer_choice == "scissors":
return "player"
else:
return "computer"
elif player_choice == "paper":
if computer_choice == "rock":
return "player"
else:
return "computer"
elif player_choice == "scissors":
if computer_choice == "paper":
return "player"
else:
return "computer"
def display_result(player_choice, computer_choice, winner):
"""Displays the choices and the result of the round."""
print("Computer chose:", computer_choice)
print("You chose:", player_choice)
if winner == "tie":
print("It's a tie!That's why ")
elif winner == "player":
if player_choice == "rock" and computer_choice == "scissors":
print("Rock crushes scissors! That said, you win! Worth adding: ")
elif player_choice == "paper" and computer_choice == "rock":
print("Paper covers rock! Because of that, you win! ")
elif player_choice == "scissors" and computer_choice == "paper":
print("Scissors cuts paper! You win!")
elif winner == "computer":
if computer_choice == "rock" and player_choice == "scissors":
print("Rock crushes scissors! You lose.In practice, ")
elif computer_choice == "paper" and player_choice == "rock":
print("Paper covers rock! Practically speaking, you lose. ")
elif computer_choice == "scissors" and player_choice == "paper":
print("Scissors cuts paper! You lose.
def main():
choices = ["rock", "paper", "scissors"]
playing = True
player_wins = 0
computer_wins = 0
ties = 0
while playing:
player_choice = get_player_choice()
if player_choice == "quit":
playing = False
print("Thanks for playing!")
break
computer_choice = random.choice(choices)
winner = determine_winner(player_choice, computer_choice)
display_result(player_choice, computer_choice, winner)
if winner == "player":
player_wins += 1
elif winner == "computer":
computer_wins += 1
else:
ties += 1
print("\n--- Final Score ---")
print("Player wins:", player_wins)
print("Computer wins:", computer_wins)
print("Ties:", ties)
if __name__ == "__main__":
main()
Key improvements:
get_player_choice()function: This function is responsible for getting the player's choice and validating the input. It returns the player's choice if it's valid, or "quit" if the player wants to exit.determine_winner()function: This function takes the player's choice and the computer's choice as input and returns "player", "computer", or "tie" depending on who won. This isolates the winning logic, making it easier to understand and modify.display_result()function: This function takes the player's choice, the computer's choice, and the winner as input and prints the result to the console. This separates the display logic from the game logic.- Simplified
main()function: Themain()function is now much cleaner and easier to follow. It calls the other functions to handle the different aspects of the game. The use of these smaller, focused functions makes the code more modular, readable, and testable.
Further Enhancements and Considerations
Here are some ideas for further enhancing the Rock Paper Scissors game:
- Best of N rounds: Implement a "best of N" rounds system (e.g., best of 3, best of 5) where the first player to win a certain number of rounds wins the game.
- AI improvements: Instead of the computer making completely random choices, you could implement a simple AI that analyzes the player's previous choices and tries to predict their next move. This could involve storing a history of the player's choices and using that to make a more informed decision. This would significantly increase the complexity and challenge of the game.
- Graphical User Interface (GUI): Instead of a text-based interface, you could create a GUI using libraries like Tkinter or PyQt. This would make the game more visually appealing and user-friendly. Players could click buttons to choose their move instead of typing it in.
- Multiplayer mode: Allow two players to play against each other, either on the same computer or over a network.
- Expand the choices: Add more choices to the game, such as "Lizard" and "Spock" (as popularized by the TV show The Big Bang Theory), which adds more complex winning conditions.
- Implement a scoring system with persistent storage: Save the high scores to a file so they are not lost when the program closes.
- Add sound effects: Use a library like
pygameto add sound effects to the game, making it more engaging. - Implement unit tests: Write unit tests to check that the game logic is working correctly. This is a crucial step in software development to ensure the reliability of your code.
Conclusion
This practical guide has walked you through the process of creating a Rock Paper Scissors game using CodeHS and Python. Starting with the basic game logic, we progressively added features like a game loop, input validation, a scoring system, and code refactoring. By understanding the concepts presented in this guide, you'll not only have a working Rock Paper Scissors game but also a solid foundation for building more complex and engaging programs in the future. Remember to experiment with the code, explore the suggested enhancements, and most importantly, have fun!