diff --git a/.gitignore b/.gitignore index 7560965..6cb7c1c 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ *.dll *.so *.dylib +roll # Test binary, build with `go test -c` *.test diff --git a/main.go b/main.go new file mode 100644 index 0000000..305cfaa --- /dev/null +++ b/main.go @@ -0,0 +1,73 @@ +package main + +import ( + "fmt" + "math/rand" + "os" + "strconv" + "strings" + "time" +) + +var r *rand.Rand + +func main() { + parm := "1d20" + if len(os.Args) > 0 { + if len(os.Args) == 2 { + parm = os.Args[1] + } else if len(os.Args) == 3 { + parm = os.Args[1] + "d" + os.Args[2] + } + } + + r = rand.New(rand.NewSource(time.Now().UnixNano())) + num, sides, times := parseParm(parm) + for i := times; i > 0; i-- { + if times > 1 { + fmt.Printf("%d: ", times-i+1) + } + fmt.Println(roll(num, sides)) + } +} + +func parseParm(p string) (int, int, int) { + var pts []string + if strings.Contains(p, "d") { + pts = strings.Split(p, "d") + } + var num, sides int + if len(pts) > 0 { + num = atoi(pts[0]) + } + times := 1 + if len(pts) > 1 { + if strings.Contains(pts[1], "x") { + thesepts := strings.Split(pts[1], "x") + if len(thesepts) > 1 { + sides = atoi(thesepts[0]) + times = atoi(thesepts[1]) + } + } else { + sides = atoi(pts[1]) + } + } + return num, sides, times +} + +func roll(num, sides int) int { + ret := 0 + for ; num > 0; num-- { + ret += r.Intn(sides) + } + return ret +} + +func atoi(a string) int { + ret, err := strconv.Atoi(a) + if err != nil { + fmt.Println("Error parsing value:", a) + os.Exit(1) + } + return ret +}