Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Golang Bot

package main

import (
	"fmt"
	"os"
	"bufio"
	"strings"
	"time"
	"math/rand"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	fmt.Println("Enter a move (rock, lizard, paper, spock, scissors):")
	move, _ := reader.ReadString('\n')

	// Trim string
	move = strings.TrimSpace(move)

	// Have the bot make the moves
	possibleMoves := []string{"rock", "lizard", "paper", "spock", "scissors"}

	// Generate random num
	rand.Seed(time.Now().UTC().UnixNano())
	botMove := possibleMoves[randInt(0, len(possibleMoves) - 1)]

	fmt.Println("The bot guessed", botMove)

	// Calculate outcome
	switch move {
	case "rock":
		if botMove == "scissors" || botMove == "lizard" {
			win()
		} else {
			lose()
		}
	case "lizard":
		if botMove == "spock" || botMove == "paper" {
			win()
		} else {
			lose()
		}
	case "paper":
		if botMove == "rock" || botMove == "spock" {
			win()
		} else {
			lose()
		}
	case "spock":
		if botMove == "scissors" || botMove == "rock" {
			win()
		} else {
			lose()
		}
	case "scissors":
		if botMove == "paper" || botMove == "lizard" {
			win()
		} else {
			lose()
		}
	}
}

func win() {
	fmt.Println("Congratulations, you won!")
}

func lose() {
	fmt.Println("You lost! Too bad.")
}

func randInt(min int, max int) int {
    return min + rand.Intn(max-min)
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.