Welcome to the Rock, Paper, Scissors game! This simple game lets you play against the computer in the classic hand game of Rock, Paper, Scissors. The goal of the game is to choose one of the three options (rock, paper, or scissors) and compare it with the computer’s choice to determine the winner. The rules are as follows:
- Rock beats Scissors.
- Scissors beats Paper.
- Paper beats Rock.
Objective
The objective of this program is to provide a basic implementation of the Rock, Paper, Scissors game in the Go programming language. It demonstrates the use of random number generation, basic input and output, and conditional statements to control the game flow.
Go Code: Rock, Paper, Scissors Game
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func main() {
// Seed the random number generator
rand.Seed(time.Now().UnixNano())
// Define the choices
choices := []string{"rock", "paper", "scissors"}
// Prompt the user to enter their choice
fmt.Println("Welcome to Rock, Paper, Scissors!")
fmt.Print("Enter your choice (rock, paper, or scissors): ")
var userChoice string
fmt.Scanln(&userChoice)
userChoice = strings.ToLower(userChoice)
// Validate user input
if userChoice != "rock" && userChoice != "paper" && userChoice != "scissors" {
fmt.Println("Invalid choice. Please enter rock, paper, or scissors.")
return
}
// Generate the computer's choice
computerChoice := choices[rand.Intn(len(choices))]
// Display choices
fmt.Println("Your choice:", userChoice)
fmt.Println("Computer's choice:", computerChoice)
// Determine the winner
if userChoice == computerChoice {
fmt.Println("It's a tie!")
} else if (userChoice == "rock" && computerChoice == "scissors") ||
(userChoice == "scissors" && computerChoice == "paper") ||
(userChoice == "paper" && computerChoice == "rock") {
fmt.Println("You win!")
} else {
fmt.Println("Computer wins!")
}
}
Program Explanation
The program follows these basic steps:
- The user is prompted to enter their choice (rock, paper, or scissors).
- The program checks the user’s input for validity and ensures it’s one of the three options.
- The computer randomly selects one of the three choices using the
rand
package. - Both the user’s and the computer’s choices are displayed.
- The winner is determined based on the rules of Rock, Paper, Scissors, and the result is displayed.
How to Run the Program
To run this program on your local machine, you need to have Go installed. Follow these steps:
- Download and install Go from here.
- Save the above Go code in a file named
rock_paper_scissors.go
. - Open a terminal or command prompt and navigate to the directory where you saved the file.
- Run the program using the command:
go run rock_paper_scissors.go
. - Follow the on-screen instructions to play the game.