Skip to content

Instantly share code, notes, and snippets.

@sebastianwebber sebastianwebber/README.md
Last active Feb 19, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.