small experiment on our go meetup.
Last active
February 19, 2019 02:36
-
-
Save sebastianwebber/17d437697128923ef3c266c253655ebc to your computer and use it in GitHub Desktop.
go animal race
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" | |
"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