Python Algorithm For Rock, Paper & Scissor

Python Algorithm For Rock, Paper & Scissor

Introduction

Rock, paper, scissors is a hand game usually played between two people, in which each player simultaneously forms one of three shapes with their hand: a rock (a closed fist), a paper (a flat hand), or scissors (two fingers extended). The game proceeds as follows:

  1. The two players simultaneously choose one of the three shapes.
  2. The shapes are then compared to determine the winner.
  3. Rock beats scissors, scissors beats paper, and paper beats rock.
  4. If both players choose the same shape, the game is a tie.

The game is a zero-sum game, meaning that one player’s win is the other player’s loss. Rock, paper, scissors is a simple game, but it is also a very strategic game. There are many different strategies that can be used to win the game, and the best strategy will vary depending on the opponent.

Easy way around to write python algorithm for rock, paper & scissor

import random

def rock_paper_scissors():
“””
Plays a game of rock, paper, scissors.

Returns:
The winner of the game.
“””

choices = [“rock”, “paper”, “scissors”]
computer_choice = random.choice(choices)
player_choice = input(“Choose rock, paper, or scissors: “)

if player_choice not in choices:
print(“Invalid choice!”)
return None

if player_choice == computer_choice:
return “Tie”

if (player_choice == “rock” and computer_choice == “scissors”) or (
player_choice == “paper” and computer_choice == “rock”) or (
player_choice == “scissors” and computer_choice == “paper”):
return “Player”

return “Computer”

def main():
winner = rock_paper_scissors()
if winner == “Player”:
print(“You won!”)
elif winner == “Computer”:
print(“Computer won!”)
else:
print(“Tie!”)

if __name__ == “__main__”:
main()

Explanation

This code implements a game of rock, paper, scissors. The code first defines a function called rock_paper_scissors(). The rock_paper_scissors() function takes no arguments and returns the winner of the game. The function first generates a random choice for the computer. The function then prompts the player to make a choice. The function then compares the player’s choice to the computer’s choice and determines the winner.

The code then defines a function called main(). The main() function calls the rock_paper_scissors() function and prints the winner of the game.

Leave a comment