summaryrefslogtreecommitdiff
path: root/roll.go
blob: 414b0d20e7a3b4173a0176181b585860f68c8d83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/* Copyright (C) 2011, 2013-2014, 2017 Luke Shumaker <lukeshu@sbcglobal.net> */
package main

import (
	"crypto/rand"
	"fmt"
	"math/big"
	"os"
	"regexp"
	"strconv"
)

func usage() {
	fmt.Printf("Arguments are in the format [<COUNT>]d<SIZE>[+<MOD>]\n")
}

func rollDie(size int) int {
	num, err := rand.Int(rand.Reader, big.NewInt(int64(size)))
	if err != nil {
		panic(err)
	}
	return int(num.Int64()) + 1
}

func roll(input string) {
	parser := regexp.MustCompile("^([0-9]*)d([0-9]+)([+-][0-9]+)?$")
	parts := parser.FindStringSubmatch(input)
	if len(parts) < 2 {
		usage()
		return
	}
	dice, _ := strconv.Atoi(parts[1])
	die_size, _ := strconv.Atoi(parts[2])
	mod := 0
	if len(parts) > 3 {
		mod, _ = strconv.Atoi(parts[3])
	}
	if dice < 1 {
		dice = 1
	}

	total := 0
	for i := 0; i < dice; i++ {
		v := rollDie(die_size)
		fmt.Printf("%d+", v)
		total += v
	}
	total += mod
	fmt.Printf("%d = %d\n", mod, total)
}

func main() {
	if len(os.Args) == 1 {
		usage()
	}
	args := os.Args[1:]
	for _, arg := range args {
		roll(arg)
	}
}