Skip to content

Instantly share code, notes, and snippets.

@sebastianwebber
Last active February 19, 2019 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastianwebber/17d437697128923ef3c266c253655ebc to your computer and use it in GitHub Desktop.
Save sebastianwebber/17d437697128923ef3c266c253655ebc to your computer and use it in GitHub Desktop.
go animal race

Race

small experiment on our go meetup.

tty-min

package main
import (
"fmt"
"math/rand"
"os"
"os/exec"
"sort"
"strings"
"time"
)
func clearScreen() {
// https://stackoverflow.com/questions/22891644/how-can-i-clear-the-terminal-screen-in-go
// fmt.Println("\033[2J")
cmd := exec.Command("clear") //Linux example, its tested
cmd.Stdout = os.Stdout
cmd.Run()
}
const maxSteps = 50
func sortKeys(input map[string]int) []string {
var keys []string
for k := range input {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
func main() {
clearScreen()
players := map[string]int{
"cavalo": 0,
"porco": 0,
"leopardo": 0,
}
sortedKeys := sortKeys(players)
exit := false
champ := ""
for {
for _, k := range sortedKeys {
players[k] += rand.Intn(5)
}
for _, k := range sortedKeys {
if !exit && players[k] >= maxSteps {
exit = true
champ = k
}
corre(k, players[k])
}
if exit {
break
}
time.Sleep(500 * time.Millisecond)
clearScreen()
}
fmt.Printf("\n %s win with %d steps.\n", champ, players[champ])
}
func corre(nome string, passos int) {
fmt.Printf("%15s: %s\n", nome, strings.Repeat("#", passos))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment