74 lines
1.2 KiB
Go
74 lines
1.2 KiB
Go
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
|
|
}
|