Rock Paper Scissors Game: Python Code & How to Play
Rock Paper Scissors Game: A Simple Python Implementation
This is a straightforward implementation of the classic Rock Paper Scissors game. You can play it against another person, or even against a computer using the provided Python code.
The Rules of the Game
- Rock beats Scissors
- Scissors beats Paper
- Paper beats Rock
How to Play
- Choose your weapon: Both players (or a player and the computer) choose 'r' (rock), 'p' (paper), or 's' (scissors) to represent their selection.
- Compare and declare the winner: The winner is determined based on the rules outlined above.
Code Implementation (Python)
import random
def game():
print("Welcome to Rock Paper Scissors!")
player1 = input("Player 1, please choose rock (r), paper (p) or scissors (s): ")
player2 = input("Player 2, please choose rock (r), paper (p) or scissors (s): ")
choices = ["r", "p", "s"]
computer_choice = random.choice(choices)
print(f"Computer chooses {computer_choice}")
if player1 == player2:
print("It's a tie!")
elif player1 == "r":
if player2 == "s":
print("Player 1 wins!")
else:
print("Player 2 wins!")
elif player1 == "p":
if player2 == "r":
print("Player 1 wins!")
else:
print("Player 2 wins!")
elif player1 == "s":
if player2 == "p":
print("Player 1 wins!")
else:
print("Player 2 wins!")
else:
print("Invalid input, please try again.")
game()
game()
Let's break down the Python code:
import random: This line imports therandommodule, which is essential for generating the computer's choice.def game():: This line defines a function namedgame(), which will hold the logic of the game.print("Welcome to Rock Paper Scissors!"): This line displays a welcoming message to the players.player1 = input("Player 1, please choose rock (r), paper (p) or scissors (s): "): This line prompts Player 1 to enter their choice.player2 = input("Player 2, please choose rock (r), paper (p) or scissors (s): "): This line prompts Player 2 to enter their choice.choices = ["r", "p", "s"]: This line creates a list containing the possible choices (rock, paper, scissors).computer_choice = random.choice(choices): This line randomly selects a choice for the computer from thechoiceslist.print(f"Computer chooses {computer_choice}"): This line displays the computer's choice to the players.if player1 == player2:: This line checks if both players chose the same option. If they did, it's a tie.elif player1 == "r":and so on: These lines useelifstatements to determine the winner based on the rules of the game.print("Invalid input, please try again."): This line handles invalid user input and prompts the player to try again.game(): This line recursively calls thegame()function if there is invalid input, starting the game again.game(): This line calls thegame()function to start the game when the script is run.
Now you can copy and paste the code into a Python interpreter or a Python file and run it to play the game!
原文地址: https://www.cveoy.top/t/topic/lmns 著作权归作者所有。请勿转载和采集!