-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrock-paper-scissor.go
76 lines (68 loc) · 1.46 KB
/
rock-paper-scissor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
func main() {
reader := bufio.NewReader(os.Stdin)
// Set up game
rand.Seed(time.Now().UnixNano())
choices := []string{"rock", "paper", "scissors"}
wins := [][]int{
{0, 1, -1},
{-1, 0, 1},
{1, -1, 0},
}
// Play game
fmt.Println("Let's play Rock-Paper-Scissors!")
for {
// Get player choice
fmt.Print("Enter your choice (rock/paper/scissors): ")
playerChoice, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading input:", err)
continue
}
playerChoice = strings.TrimSpace(playerChoice)
// Check player choice is valid
playerIndex := -1
for i, choice := range choices {
if choice == playerChoice {
playerIndex = i
break
}
}
if playerIndex == -1 {
fmt.Println("Invalid choice, please enter rock, paper, or scissors.")
continue
}
// Get computer choice
computerIndex := rand.Intn(3)
fmt.Println("Computer chose", choices[computerIndex])
// Determine winner
result := wins[playerIndex][computerIndex]
switch result {
case 1:
fmt.Println("You win!")
case 0:
fmt.Println("It's a tie!")
case -1:
fmt.Println("Computer wins!")
}
// Ask if player wants to play again
fmt.Print("Play again? (y/n): ")
playAgain, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading input:", err)
continue
}
playAgain = strings.TrimSpace(playAgain)
if playAgain != "y" {
break
}
}
}