forked from travis-g/dice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modifier.go
371 lines (330 loc) · 9.29 KB
/
modifier.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package dice
import (
"context"
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
"github.com/pkg/errors"
)
// MaxRerolls is the maximum number of rerolls allowed on a given die.
var MaxRerolls = 1000
// A Modifier is a dice modifier that can apply to a set or a single die.
type Modifier interface {
// Apply executes a modifier against a Die.
Apply(context.Context, Roller) error
fmt.Stringer
}
// ModifierList is a slice of modifiers that implements Stringer.
type ModifierList []Modifier
func (m ModifierList) String() string {
var b strings.Builder
for _, mod := range m {
b.WriteString(mod.String())
}
return b.String()
}
// CompareOp is an comparison operator usable in modifiers.
type CompareOp int
// Comparison operators.
const (
EMPTY CompareOp = iota
compareOpStart
EQL // =
LSS // <
GTR // >
LEQ // <=
GEQ // >=
compareOpEnd
)
var compares = [...]string{
EMPTY: "",
EQL: "=",
LSS: "<",
GTR: ">",
LEQ: "<=",
GEQ: ">=",
}
var compareStringMap map[string]CompareOp
// Initialize the compareStringMap for LookupCompareOp
func init() {
compareStringMap = make(map[string]CompareOp)
for i := compareOpStart + 1; i < compareOpEnd; i++ {
compareStringMap[compares[i]] = i
}
}
// LookupCompareOp returns the CompareOp that is represented by a given string.
func LookupCompareOp(s string) CompareOp {
return compareStringMap[s]
}
func (c CompareOp) String() string {
s := ""
if 0 <= c && c < CompareOp(len(compares)) {
s = compares[c]
}
return s
}
// MarshalJSON ensures the CompareOp is encoded as its string representation.
func (c *CompareOp) MarshalJSON() ([]byte, error) {
return json.Marshal(c.String())
}
// UnmarshalJSON enables JSON encoded string versions of CompareOps to be
// converted to their appropriate counterparts.
func (c *CompareOp) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err != nil {
return errors.Wrap(err, "error unmarshaling json to CompareOp")
}
*c = LookupCompareOp(str)
return nil
}
// CompareTarget is the base comparison
type CompareTarget struct {
Compare CompareOp `json:"compare,omitempty"`
Target int `json:"target"`
}
// RerollModifier is a modifier that rerolls a Die if a comparison against the
// compare target is true.
type RerollModifier struct {
*CompareTarget
Once bool `json:"once,omitempty"`
}
// MarshalJSON marshals the modifier into JSON and includes an internal type
// property.
func (m *RerollModifier) MarshalJSON() ([]byte, error) {
type Faux RerollModifier
return json.Marshal(&struct {
Type string `json:"type"`
*Faux
}{
Type: "reroll",
Faux: (*Faux)(m),
})
}
func (m *RerollModifier) String() string {
var b strings.Builder
write := b.WriteString
write("r")
// inferred equals if not specified
if m.Compare != EQL {
write(m.Compare.String())
}
write(strconv.Itoa(m.Target))
return b.String()
}
// Apply executes a RerollModifier against a Roller. The modifier may be
// slightly modified the first time it is applied to ensure property
// consistency.
//
// The full roll needs to be recalculated in the event that one result may be
// acceptable for one reroll criteria, but not for one that was already
// evaluated. An ErrRerolled error will be returned if the die was rerolled in
// case other modifiers on the die need to be reapplied. Impossible rerolls and
// impossible combinations of rerolls may cause a stack overflow from recursion
// without a safeguard like MaxRerolls.
func (m *RerollModifier) Apply(ctx context.Context, r Roller) error {
if m == nil {
return errors.New("nil modifier")
}
if m.Compare == EMPTY {
m.Compare = EQL
}
ok, err := m.Valid(ctx, r)
if err != nil {
return err
}
if ok {
return nil
}
// if once, do only once
if m.Once {
return r.Reroll(ctx)
}
// reroll until valid
return rerollApplyTail(ctx, m, r)
}
// rerollApplyTail is a tail-recursive function to reroll a die based on a
// modifier. The error returned must be an ErrRerolled to indicate the die was
// changed via rerolling. ErrRerolled may need to bubble up to the rollable's
// core rolling functions to indicate other modifiers must be reapplied.
//
// Tail recursion is used here as the stack has the potential to grow quite
// large if the recursive calls are not optimized.
func rerollApplyTail(ctx context.Context, m *RerollModifier, r Roller) error {
if m == nil {
return errors.New("nil modifier")
}
if err := r.Reroll(ctx); err != nil {
return err
}
ok, err := m.Valid(ctx, r)
if err != nil {
return err
}
// Now that die has settled, return rerolled error
if ok {
return ErrRerolled
}
return rerollApplyTail(ctx, m, r)
}
// Valid checks if the supplied die is valid against the modifier. If not valid
// the reroll modifier should be applied, unless there is an error.
func (m *RerollModifier) Valid(ctx context.Context, r Roller) (bool, error) {
if m == nil {
return false, errors.New("nil modifier")
}
var (
result float64
err error
)
if m.Compare == EMPTY {
m.Compare = EQL
}
if result, err = r.Total(ctx); err != nil {
// return invalid if error
return false, err
}
switch m.Compare {
// until the comparison operation succeeds and the reroll passes, keep
// rerolling.
case EQL:
return result != float64(m.Target), nil
case LSS, LEQ:
return !(result <= float64(m.Target)), nil
case GTR, GEQ:
return !(result >= float64(m.Target)), nil
default:
err = &ErrNotImplemented{
fmt.Sprintf("uncaught case for reroll compare: %s", m.Compare),
}
return false, err
}
}
// A DropKeepMethod is a method to use when evaluating a drop/keep modifier
// against a dice group.
type DropKeepMethod string
// Drop/keep methods.
const (
DropKeepMethodUnknown DropKeepMethod = ""
DropKeepMethodDrop DropKeepMethod = "d"
DropKeepMethodDropLowest DropKeepMethod = "dl"
DropKeepMethodDropHighest DropKeepMethod = "dh"
DropKeepMethodKeep DropKeepMethod = "k"
DropKeepMethodKeepLowest DropKeepMethod = "kl"
DropKeepMethodKeepHighest DropKeepMethod = "kh"
)
// A DropKeepModifier is a modifier to drop the highest or lowest Num dice
// within a group by marking them as Dropped. The Method used to apply the
// modifier defines if the dice are dropped or kept (meaning the Num highest
// dice are not dropped).
type DropKeepModifier struct {
Method DropKeepMethod `json:"op,omitempty"`
Num int `json:"num"`
}
func (d *DropKeepModifier) String() string {
return string(d.Method)
}
// Apply executes a DropKeepModifier against a Roller. If the Roller is not a
// Group an error is returned.
func (d *DropKeepModifier) Apply(ctx context.Context, r Roller) error {
group, ok := r.(*RollerGroup)
if !ok {
return errors.New("target for modifier not a dice group")
}
// create a duplicate of the slice to sort
dice := group.Copy()
// TODO: do these dice need to be sorted by their result value/should
// already-dropped dice be filtered and excluded?
sort.Slice(dice, func(i, j int) bool {
ti, _ := (dice[i]).Total(ctx)
tj, _ := (dice[j]).Total(ctx)
return ti < tj
})
switch d.Method {
case DropKeepMethodDrop, DropKeepMethodDropLowest:
// drop lowest Num
for i := 0; i < d.Num && i < len(dice); i++ {
dice[i].Drop(ctx, true)
}
case DropKeepMethodKeep, DropKeepMethodKeepHighest:
// drop all but highest Num
for i := 0; i < len(dice)-d.Num && i < len(dice); i++ {
dice[i].Drop(ctx, true)
}
case DropKeepMethodDropHighest:
for i := len(dice) - d.Num; i < len(dice) && i < len(dice); i++ {
dice[i].Drop(ctx, true)
}
case DropKeepMethodKeepLowest:
for i := d.Num; i < len(dice) && i < len(dice); i++ {
dice[i].Drop(ctx, true)
}
default:
return &ErrNotImplemented{"unknown drop/keep method"}
}
return nil
}
// A CriticalSuccessModifier shifts or sets the compare point/range used to
// classify a die's result as a critical success.
type CriticalSuccessModifier struct {
*CompareTarget
}
func (m *CriticalSuccessModifier) String() string {
var b strings.Builder
write := b.WriteString
write("cs")
// inferred equals if not specified
if m.Compare != EQL {
write(m.Compare.String())
}
write(strconv.Itoa(m.Target))
return b.String()
}
// A CriticalFailureModifier shifts or sets the compare point/range used to
// classify a die's result as a critical failure.
type CriticalFailureModifier struct {
*CompareTarget
}
func (m *CriticalFailureModifier) String() string {
var b strings.Builder
write := b.WriteString
write("cf")
// inferred equals if not specified
if m.Compare != EQL {
write(m.Compare.String())
}
write(strconv.Itoa(m.Target))
return b.String()
}
// SortDirection is a possible direction for sorting dice.
type SortDirection uint8
// Sort directions for sorting modifiers.
const (
SortDirectionAscending SortDirection = iota
SortDirectionDescending
)
// SortModifier is a modifier that will sort the Roller group.
type SortModifier struct {
Direction SortDirection `json:"direction"`
}
func (s *SortModifier) String() string {
if s.Direction == SortDirectionDescending {
return "sd"
}
return "s"
}
// Apply applies a sort to a Roller.
func (s *SortModifier) Apply(ctx context.Context, r Roller) error {
group, ok := r.(*RollerGroup)
if !ok {
return errors.New("target for modifier not a dice group")
}
switch s.Direction {
case SortDirectionAscending:
sort.Sort(group.Group)
case SortDirectionDescending:
sort.Sort(sort.Reverse(group.Group))
}
return nil
}