-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast.go
535 lines (452 loc) · 11.9 KB
/
ast.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
package roll
import (
"fmt"
"sort"
"strconv"
"strings"
)
// ComparisonType is the type of comparison
type ComparisonType int
const (
// Equals matches only values that are equal to the comparison value
Equals ComparisonType = iota
// GreaterThan matches only values greater than the comparison value
GreaterThan
// LessThan matches only values less than the comparison value
LessThan
)
// ComparisonOp is the operation that defines how you compare against a roll
// to determine whether the result counts
type ComparisonOp struct {
Type ComparisonType
Value int
}
// Match returns true if the given value compares positively against the op val
func (op *ComparisonOp) Match(val int) bool {
switch op.Type {
case Equals:
return val == op.Value
case GreaterThan:
return val > op.Value
case LessThan:
return val < op.Value
}
return false
}
// String returns the string representation of the comparison operator
func (op *ComparisonOp) String() string {
switch op.Type {
case Equals:
return fmt.Sprintf("=%d", op.Value)
case GreaterThan:
return fmt.Sprintf(">%d", op.Value)
case LessThan:
return fmt.Sprintf("<%d", op.Value)
}
return ""
}
// ExplodingType is the type of exploding die
type ExplodingType int
const (
// Exploding adds new dice for each roll satisfying the exploding condition
Exploding ExplodingType = iota
// Compounded adds to a single new result for each roll
Compounded
// Penetrating is like Exploding, except each die result has a -1 modifier
Penetrating
)
// ExplodingOp is the operation that defines how a dice roll explodes
type ExplodingOp struct {
*ComparisonOp
Type ExplodingType
}
// String returns the string representation of the exploding dice operation
func (e ExplodingOp) String() (output string) {
switch e.Type {
case Exploding:
output = "!"
case Compounded:
output = "!!"
case Penetrating:
output = "!p"
}
return output + strings.TrimPrefix(e.ComparisonOp.String(), "=")
}
// LimitType is the type of roll limitation
type LimitType int
const (
// KeepHighest indicated we should keep the highest results
KeepHighest LimitType = iota
// KeepLowest indicated we should keep the lowest results
KeepLowest
// DropHighest indicated we should drop the highest results
DropHighest
// DropLowest indicated we should drop the lowest results
DropLowest
)
// LimitOp is the operation that defines how dice roll results are limited
type LimitOp struct {
Amount int
Type LimitType
}
func (op LimitOp) String() (output string) {
switch op.Type {
case KeepHighest:
output = "kh"
case KeepLowest:
output = "kl"
case DropHighest:
output = "dh"
case DropLowest:
output = "dl"
}
if op.Amount > 1 {
output += strconv.Itoa(op.Amount)
}
return
}
// RerollOp is the operation that defines how dice are rerolled
type RerollOp struct {
*ComparisonOp
Once bool
}
// String returns the string representation of the exploding dice operation
func (e RerollOp) String() (output string) {
output = "r"
if e.Once {
output = "ro"
}
return output + strings.TrimPrefix(e.ComparisonOp.String(), "=")
}
// SortType is the type of sorting to use for dice roll results
type SortType int
// String return the string representation of a SortType value
func (t SortType) String() string {
switch t {
case Unsorted:
return ""
case Ascending:
return "s"
case Descending:
return "sd"
}
return ""
}
const (
// Unsorted doesn't sort dice rolls
Unsorted SortType = iota
// Ascending sorts dice rolls from lowest to highest
Ascending
// Descending sorts dice rolls from highest to lowest
Descending
)
// Roll is any kind of roll
type Roll interface {
Roll() Result
String() string
}
// Result is a collection of die rolls and a count of successes
type Result struct {
Results []DieRoll
Total int
Successes int
}
// Len is the number of results
func (r *Result) Len() int {
return len(r.Results)
}
// Less return true if DieRoll at index i is less than the one at index j
func (r *Result) Less(i, j int) bool {
return r.Results[i].Result < r.Results[j].Result
}
// Swap swaps the DieRoll at index i with the one at index j
func (r *Result) Swap(i, j int) {
r.Results[i], r.Results[j] = r.Results[j], r.Results[i]
}
// DiceRoll is an individual Dice Roll
type DiceRoll struct {
Multiplier int
Die Die
Modifier int
Exploding *ExplodingOp
Limit *LimitOp
Success *ComparisonOp
Failure *ComparisonOp
Rerolls []RerollOp
Sort SortType
}
// Roll gets the results of rolling the dice that make up a dice roll
func (dr *DiceRoll) Roll() (result Result) {
// 1. Do Multiplier rolls of Die
if dr.Multiplier == 0 {
return
}
totalMultiplier := 1
if dr.Multiplier < 0 {
totalMultiplier = -1
}
for i := 0; i < dr.Multiplier*totalMultiplier; i++ {
result.Results = append(result.Results, dr.Die.Roll())
}
// 2. For each result, check reroll criteria and reroll if a match
for i, roll := range result.Results {
RerollOnce:
for _, reroll := range dr.Rerolls {
for reroll.Match(roll.Result) {
roll = dr.Die.Roll()
result.Results[i] = roll
if reroll.Once {
break RerollOnce
}
}
}
}
// 3. For each result, check exploding criteria and generate new rolls
if dr.Exploding != nil {
switch dr.Exploding.Type {
case Exploding:
for _, roll := range result.Results {
for dr.Exploding.Match(roll.Result) {
roll = dr.Die.Roll()
result.Results = append(result.Results, roll)
}
}
case Compounded:
compound := 0
for _, roll := range result.Results {
for dr.Exploding.Match(roll.Result) {
compound += roll.Result
roll = dr.Die.Roll()
}
}
result.Results = append(result.Results, DieRoll{compound, strconv.Itoa(compound)})
case Penetrating:
for _, roll := range result.Results {
for dr.Exploding.Match(roll.Result) {
roll = dr.Die.Roll()
newroll := roll
newroll.Result--
newroll.Symbol = strconv.Itoa(newroll.Result)
result.Results = append(result.Results, newroll)
}
}
}
}
// 4. Check results and apply limit operation
applyLimit(dr.Limit, &result)
// 5. If success op set, add modifier to each result and add successes for each match
applySuccess(dr.Success, dr.Modifier, &result)
// 6. If failure op set, add modifier to each result and subtract successes for each match
applyFailure(dr.Failure, dr.Modifier, &result)
// 7. If sort op set, sort results
applySort(dr.Sort, &result)
// 8. If success and failure ops not set, add modifier to total result
finaliseTotals(dr.Success, dr.Failure, dr.Modifier, totalMultiplier, &result)
return
}
// String represents the dice roll as a string
func (dr *DiceRoll) String() string {
var output string
if dr.Multiplier > 1 || dr.Multiplier < -1 {
output += fmt.Sprintf("%+d", dr.Multiplier)
} else if dr.Multiplier == -1 {
output += "-"
} else if dr.Multiplier == 1 {
output += "+"
}
output += dr.Die.String()
if dr.Modifier != 0 {
output += fmt.Sprintf("%+d", dr.Modifier)
}
for _, r := range dr.Rerolls {
output += r.String()
}
if dr.Exploding != nil {
output += (*dr.Exploding).String()
}
if dr.Limit != nil {
output += (*dr.Limit).String()
}
if dr.Success != nil {
output += (*dr.Success).String()
}
if dr.Failure != nil {
output += "f" + (*dr.Failure).String()
}
output += dr.Sort.String()
return output
}
// GroupedRoll is a group of other rolls. You can have nested groups.
type GroupedRoll struct {
Rolls []Roll
Modifier int
Limit *LimitOp
Success *ComparisonOp
Failure *ComparisonOp
Combined bool
Negative bool
}
// Roll gets the results of rolling the dice that make up a dice roll
func (gr *GroupedRoll) Roll() (result Result) {
// 1. Generate results for each roll
for _, roll := range gr.Rolls {
if gr.Combined {
// 2. If combined, merge all roll results into one result set
// NOTE: in combined mode, the roll modifier is added to each result
var mod int
switch t := roll.(type) {
case *GroupedRoll:
mod = t.Modifier
case *DiceRoll:
mod = t.Modifier
}
for _, res := range roll.Roll().Results {
result.Results = append(result.Results, DieRoll{
res.Result + mod,
strconv.Itoa(res.Result + mod),
})
}
} else {
// 3. If not combined, make new result set out of the totals for each roll
total := roll.Roll().Total
result.Results = append(result.Results, DieRoll{total, strconv.Itoa(total)})
}
}
// 4. If limit set, apply limit operation to results
applyLimit(gr.Limit, &result)
// 5. If Success set, apply success op to results
applySuccess(gr.Success, gr.Modifier, &result)
// 6. If Failure set, apply failure op to results
applyFailure(gr.Failure, gr.Modifier, &result)
// 7. Add modifier or tally successes
finaliseTotals(gr.Success, gr.Failure, gr.Modifier, 1, &result)
if gr.Negative {
result.Total *= -1
for i, r := range result.Results {
r.Result *= -1
result.Results[i] = r
}
}
return result
}
// String represents the grouped roll as a string
func (gr *GroupedRoll) String() (output string) {
parts := []string{}
for _, roll := range gr.Rolls {
if roll != nil {
parts = append(parts, roll.String())
}
}
sep := ", "
if gr.Combined {
sep = " + "
}
output = strings.Join(parts, sep)
if gr.Combined {
output = strings.Replace(output, "+-", "-", -1)
} else if len(gr.Rolls) == 1 {
// This case should be impossible, but we want to be able to identify
// it if it *does* somehow happen.
output += ","
}
output = "{" + output + "}"
output = strings.Replace(output, "{+", "{", -1)
output = strings.Replace(output, "{-", "{", -1)
output = strings.Replace(output, ", +", ", ", -1)
output = strings.Replace(output, ", -", ", ", -1)
output = strings.Replace(output, "+ +", "+ ", -1)
output = strings.Replace(output, "+ -", "- ", -1)
if gr.Limit != nil {
output += (*gr.Limit).String()
}
if gr.Success != nil {
output += (*gr.Success).String()
}
if gr.Failure != nil {
output += "f" + (*gr.Failure).String()
}
if gr.Modifier != 0 {
output += fmt.Sprintf("%+d", gr.Modifier)
}
if gr.Negative {
output = "-" + output
}
return output
}
func applyLimit(limitOp *LimitOp, result *Result) {
if limitOp != nil {
var rolls Result
rolls.Results = result.Results[:]
// Sort our tmp result copy
sort.Sort(&rolls)
// Work out limit
limit := limitOp.Amount
if limit > len(rolls.Results) {
limit = len(rolls.Results)
}
switch limitOp.Type {
case KeepHighest:
rolls.Results = rolls.Results[len(rolls.Results)-limit:]
case KeepLowest:
rolls.Results = rolls.Results[:limit]
case DropHighest:
rolls.Results = rolls.Results[:len(rolls.Results)-limit]
case DropLowest:
rolls.Results = rolls.Results[limit:]
}
m := make(map[int]int, len(rolls.Results))
for _, r := range rolls.Results {
m[r.Result]++
}
newResults := make([]DieRoll, 0, len(rolls.Results))
for _, a := range result.Results {
if b, ok := m[a.Result]; ok {
newResults = append([]DieRoll{a}, newResults...)
b--
if b == 0 {
delete(m, a.Result)
}
}
}
result.Results = newResults
}
}
func applySuccess(successOp *ComparisonOp, modifier int, result *Result) {
if successOp != nil {
for _, roll := range result.Results {
if successOp.Match(roll.Result + modifier) {
result.Successes++
}
}
}
}
func applyFailure(failureOp *ComparisonOp, modifier int, result *Result) {
if failureOp != nil {
for _, roll := range result.Results {
if failureOp.Match(roll.Result + modifier) {
result.Successes--
}
}
}
}
func applySort(sortType SortType, result *Result) {
switch sortType {
case Unsorted:
return
case Ascending:
sort.Sort(result)
case Descending:
sort.Sort(sort.Reverse(result))
}
}
func finaliseTotals(successOp, failureOp *ComparisonOp, modifier, multiplier int, result *Result) {
if successOp == nil && failureOp == nil {
for _, roll := range result.Results {
result.Total += roll.Result
}
result.Total += modifier
result.Total *= multiplier
} else {
result.Total = result.Successes
}
}