Skip to content

Instantly share code, notes, and snippets.

@danivovich
Created September 10, 2013 20:43
Show Gist options
  • Save danivovich/6515404 to your computer and use it in GitHub Desktop.
Save danivovich/6515404 to your computer and use it in GitHub Desktop.
Chutes and Ladders in Go
package main
import (
"fmt"
"math/rand"
"os"
"text/tabwriter"
"time"
)
var winner int
var move int
func main() {
move = 0
r := rand.New(rand.NewSource(time.Now().UnixNano()))
w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
defer w.Flush()
show := func(name string, v interface{}) {
fmt.Fprintf(w, "%s\t%v\n", name, v)
}
board := make([]int, 100)
for i := 0; i < 100; i++ {
if 0 == r.Intn(2) {
board[i] = r.Intn(99 - i/2)
}
}
show("Board", board)
players := make(map[int]int)
for i := 0; i < 5; i++ {
players[i] = 0
}
winner = -1;
for winner < 0 {
player := move % len(players)
show("Player move", player)
die := r.Intn(6) + 1
players[player] += die
location := players[player]
if players[player] >= 100 {
winner = player
} else {
if board[location] > 0 {
players[player] = board[location]
}
}
show("Players", players)
move += 1
}
show("Winner", winner)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment