-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathstd.go
127 lines (109 loc) · 2.46 KB
/
std.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package dice
import (
"errors"
"fmt"
"math/rand"
"regexp"
"sort"
"strconv"
)
type StdRoller struct{}
var stdPattern = regexp.MustCompile(`([0-9]+)d([0-9]+)((k|d|kh|dl|kl|dh)([0-9]+))?([+-][0-9]+)?($|\s)`)
func (StdRoller) Pattern() *regexp.Regexp { return stdPattern }
type StdResult struct {
basicRollResult
Rolls []int
Dropped []int
Total int
}
func (r StdResult) String() string {
if (len(r.Dropped) > 0) {
return fmt.Sprintf("%d %v (%v)", r.Total, r.Rolls, r.Dropped)
} else {
return fmt.Sprintf("%d %v", r.Total, r.Rolls)
}
}
func (r StdResult) Int() int {
return r.Total
}
func (StdRoller) Roll(matches []string) (RollResult, error) {
dice, err := strconv.ParseInt(matches[1], 10, 0)
if err != nil {
return nil, err
}
sides, err := strconv.ParseInt(matches[2], 10, 0)
if err != nil {
return nil, err
}
if sides <= 0 {
return nil, errors.New("Sides must be 1 or more")
}
keep := ""
num := 0
if matches[4] != "" {
number, err := strconv.ParseInt(matches[5], 10, 0)
if err != nil {
return nil, err
}
num = int(number)
keep = matches[4]
}
result := StdResult{
basicRollResult: basicRollResult{matches[0]},
Rolls: make([]int, dice),
Dropped: nil,
Total: 0,
}
if matches[6] != "" {
bonus, err := strconv.ParseInt(matches[6], 10, 0)
if err != nil {
return nil, err
}
result.Total += int(bonus)
}
for i := 0; i < len(result.Rolls); i++ {
roll := rand.Intn(int(sides)) + 1
result.Rolls[i] = roll
}
sort.Ints(result.Rolls)
size := len(result.Rolls)
switch keep {
case "k":
fallthrough
case "kh":
slice := size - num
if slice < 0 {
return nil, errors.New("Can't keep more dice than rolled")
}
result.Dropped = result.Rolls[:slice]
result.Rolls = result.Rolls[slice:]
case "d":
fallthrough
case "dl":
if num > size {
return nil, errors.New("Can't drop more dice than rolled")
}
result.Dropped = result.Rolls[:num]
result.Rolls = result.Rolls[num:]
case "kl":
if num > size {
return nil, errors.New("Can't keep more dice than rolled")
}
result.Dropped = result.Rolls[num:]
result.Rolls = result.Rolls[:num]
case "dh":
slice := size - num
if slice < 0 {
return nil, errors.New("Can't drop more dice than rolled")
}
result.Dropped = result.Rolls[slice:]
result.Rolls = result.Rolls[:slice]
}
for i := 0; i < len(result.Rolls); i++ {
result.Total += result.Rolls[i]
}
return result, nil
}
func init() {
addRollHandler(StdRoller{})
}