This repository has been archived by the owner on Dec 5, 2023. It is now read-only.
forked from justinian/dice
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathversus.go
98 lines (78 loc) · 1.71 KB
/
versus.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
package dice
import (
"errors"
"fmt"
"math/rand"
"regexp"
"strconv"
)
type VsRoller struct{}
var vsPattern = regexp.MustCompile(`([0-9]+)d([0-9]+)(e|r)?v([0-9]+)($|\s)`)
func (VsRoller) Pattern() *regexp.Regexp { return vsPattern }
type VsResult struct {
basicRollResult
Rolls []int
Successes int
}
func (r VsResult) Description() string { return r.desc }
func (r VsResult) String() string {
return fmt.Sprintf("%d %v", r.Successes, r.Rolls)
}
func (r VsResult) Int() int {
return r.Successes
}
func (VsRoller) Roll(matches []string) (RollResult, error) {
dice, err := strconv.ParseInt(matches[1], 10, 0)
if err != nil {
return nil, err
}
if dice < 1 {
return nil, errors.New("Count must be 1 or more")
}
if dice > MaxLoop {
return nil, ErrTooManyLoops
}
sides, err := strconv.ParseInt(matches[2], 10, 0)
if err != nil {
return nil, err
}
if sides < 2 {
return nil, errors.New("Sides must be 2 or more")
}
if sides > MaxLoop {
return nil, ErrTooManyLoops
}
explode := matches[3] == "e"
reroll := matches[3] == "r"
target, err := strconv.ParseInt(matches[4], 10, 0)
if err != nil {
return nil, err
}
result := VsResult{
basicRollResult: basicRollResult{matches[0]},
Rolls: make([]int, 0, dice),
Successes: 0,
}
for i := int64(0); i < dice; i++ {
roll := rand.Intn(int(sides)) + 1
if roll == int(sides) && explode {
total := roll
for roll == int(sides) {
roll = rand.Intn(int(sides)) + 1
total += roll
}
roll = total
}
if roll == int(sides) && reroll {
i--
}
if roll >= int(target) {
result.Successes += 1
}
result.Rolls = append(result.Rolls, roll)
}
return result, nil
}
func init() {
addRollHandler(VsRoller{})
}