Skip to content

Commit

Permalink
cmd: add die roller
Browse files Browse the repository at this point in the history
  • Loading branch information
kisom committed Jun 15, 2024
1 parent 4cb6f5b commit e68d223
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions cmd/rolldie/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package main

import (
"flag"
"fmt"
"math/rand"
"os"
"regexp"
"strconv"

"git.wntrmute.dev/kyle/goutils/die"
)

var dieRollFormat = regexp.MustCompile(`^(\d+)[dD](\d+)$`)

func rollDie(count, sides int) []int {
sum := 0
var rolls []int

for i := 0; i < count; i++ {
roll := rand.Intn(sides) + 1
sum += roll
rolls = append(rolls, roll)
}

rolls = append(rolls, sum)
return rolls
}

func main() {
flag.Parse()

for _, arg := range flag.Args() {
if !dieRollFormat.MatchString(arg) {
fmt.Fprintf(os.Stderr, "invalid die format %s: should be XdY\n", arg)
os.Exit(1)
}

dieRoll := dieRollFormat.FindAllStringSubmatch(arg, -1)
count, err := strconv.Atoi(dieRoll[0][1])
die.If(err)

sides, err := strconv.Atoi(dieRoll[0][2])
die.If(err)

fmt.Println(rollDie(count, sides))
}
}

0 comments on commit e68d223

Please sign in to comment.