-
Notifications
You must be signed in to change notification settings - Fork 13
/
fudge.go
63 lines (49 loc) · 1.08 KB
/
fudge.go
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
61
62
63
package dice
import (
"fmt"
"math/rand"
"regexp"
"sort"
"strconv"
)
type FudgeRoller struct{}
var fudgePattern = regexp.MustCompile(`([0-9]+)df?([+-][0-9]+)?($|\s)`)
func (FudgeRoller) Pattern() *regexp.Regexp { return fudgePattern }
type FudgeResult struct {
basicRollResult
Rolls []int
Total int
}
func (r FudgeResult) String() string {
return fmt.Sprintf("%d %v", r.Total, r.Rolls)
}
func (r FudgeResult) Int() int {
return r.Total
}
func (FudgeRoller) Roll(matches []string) (RollResult, error) {
dice, err := strconv.ParseInt(matches[1], 10, 0)
if err != nil {
return nil, err
}
result := FudgeResult{
basicRollResult: basicRollResult{matches[0]},
Rolls: make([]int, dice),
Total: 0,
}
if matches[2] != "" {
bonus, err := strconv.ParseInt(matches[2], 10, 0)
if err != nil {
return nil, err
}
result.Total += int(bonus)
}
for i := 0; i < len(result.Rolls); i++ {
result.Rolls[i] = rand.Intn(3) - 1
result.Total += result.Rolls[i]
}
sort.Ints(result.Rolls)
return result, nil
}
func init() {
addRollHandler(FudgeRoller{})
}