Created
March 28, 2020 13:59
-
-
Save cheshir/a5705e120537782ddbbc2c6f6fe9d729 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"strings" | |
"time" | |
) | |
type turn uint8 | |
const ( | |
undefined turn = 0 | |
paper = 1 | |
scissors = 2 | |
rock = 3 | |
) | |
type gameResult uint8 | |
const ( | |
unknownResult gameResult = iota | |
draw | |
playersWin | |
computersWin | |
) | |
// todo rename me! | |
var usersTurnMap = map[string]turn{ | |
"rock": rock, | |
"камень": rock, | |
"scissors": scissors, | |
"ножницы": scissors, | |
"paper": paper, | |
"бумага": paper, | |
"бамага": paper, | |
} | |
var turnReadableNames = map[turn]string{ | |
undefined: "Undefined", | |
paper: "Paper", | |
scissors: "Scissors", | |
rock: "Rock", | |
} | |
var gameResultsReadableNames = map[gameResult]string{ | |
unknownResult: "Unknown", | |
draw: "Draw", | |
playersWin: "Players win", | |
computersWin: "Computers win", | |
} | |
func init() { | |
rand.Seed(int64(time.Now().Nanosecond())) | |
} | |
func main() { | |
fmt.Println("Hi there. Welcome to the rock scissor paper game. Make your turn.") | |
printAvailableTurns() | |
runGameRound() | |
} | |
func runGameRound() { | |
playersTurn, err := playersTurn() | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
move := computerMove() | |
fmt.Println("Computer move: ", turnReadableNames[move]) | |
result := calculateResult(playersTurn, move) | |
fmt.Println("Game result: ", gameResultsReadableNames[result]) | |
} | |
var resultTable = [][]gameResult{ | |
{draw, playersWin, computersWin}, | |
{computersWin, draw, playersWin}, | |
{playersWin, computersWin, draw}, | |
} | |
func calculateResult(playersTurn, computersTurn turn) gameResult { | |
return resultTable[computersTurn-1][playersTurn-1] | |
} | |
var possibleTurns = []turn{rock, scissors, paper} | |
func computerMove() turn { | |
index := rand.Intn(len(possibleTurns)) | |
return possibleTurns[index] | |
} | |
func playersTurn() (turn, error) { | |
var usersTurn string | |
_, err := fmt.Scanln(&usersTurn) | |
if err != nil { | |
return undefined, fmt.Errorf("failed to read users turn: %v", err) | |
} | |
result, ok := usersTurnMap[usersTurn] | |
if !ok { | |
return undefined, fmt.Errorf("unknown turn: %v", usersTurn) | |
} | |
return result, nil | |
} | |
func printAvailableTurns() { | |
availableMoves := make([]string, 0, len(usersTurnMap)) | |
for turn := range usersTurnMap { | |
availableMoves = append(availableMoves, turn) | |
} | |
fmt.Println("Available moves: ", strings.Join(availableMoves, ", ")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment