Skip to content

Instantly share code, notes, and snippets.

@ericlagergren
Last active September 12, 2015 08:00
Show Gist options
  • Save ericlagergren/6c99a9f7318116ca4b80 to your computer and use it in GitHub Desktop.
Save ericlagergren/6c99a9f7318116ca4b80 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func getInput() string {
// get input and use strings package to convert to lowercase
fmt.Print("Pick [r]ock, [p]aper, or [s]cissors: ")
var input string
fmt.Scanln(&input)
return strings.ToLower(input)
}
type Move int
const (
Rock Move = iota
Paper
Scissors
)
var validInput = map[string]Move{
"r": Rock,
"rock": Rock,
"p": Paper,
"paper": Paper,
"s": Scissors,
"scissors": Scissors,
}
var inputs = [...]string{
Rock: "Rock",
Paper: "Paper",
Scissors: "Scissors",
}
func reverseInput(move Move) string {
return inputs[move]
}
func checkInput() Move {
// start a loop until we get valid input
for {
// Does the user input match the map validInput?
if move, ok := validInput[getInput()]; ok {
fmt.Println("Player Chooses", reverseInput(move))
return move
}
fmt.Println("I didn't understand your choice, please retry")
}
}
func init() { rand.Seed(time.Now().Unix()) }
func random(min, max int) Move {
return Move(rand.Intn(max-min) + min)
}
var compare = [...]string{
Rock: "You Tied",
Paper: "You Lost :(",
Scissors: "You Win!",
}
func main() {
// Get Valid Player Input
userChoice := checkInput()
// Randomly Assign Computer Choice
computerChoice := random(0, 3)
computerInput := reverseInput(computerChoice)
fmt.Printf("Computer chooses: %s\n", computerInput)
// Check to see who won
fmt.Printf("Result: %s\n",
compare[((computerChoice-userChoice)%3+3)%3])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment