-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroll.go
125 lines (99 loc) · 2.03 KB
/
roll.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
package main
import (
"fmt"
"math/rand"
"os"
"regexp"
"strconv"
"strings"
"time"
)
func main() {
args := os.Args[1:]
if len(args) != 1 {
fmt.Println("ERROR: must have only one argument")
} else {
fmt.Println(rollDice(args[0]))
}
}
func rollDice(rolls string) int {
dice := parseRoll(rolls)
turn := NewRoll()
for _, die := range dice {
throws, sides, modifier := parseDie(die)
turn = turn.die(NewDice(sides), throws, modifier)
}
return turn.throw()
}
func parseDie(die string) (int, int, int) {
parts := strings.Split(die, "d")
// empty string is "1"
if parts[0] == "" {
parts[0] = "1"
}
// convert string to integers
times, err := strconv.ParseInt(parts[0], 0, 0)
sides, err := strconv.ParseInt(parts[1], 0, 0)
if err != nil {
panic(err)
}
modifier := int64(1)
if times < 0 {
modifier = -1
times = times * modifier
}
return int(times), int(sides), int(modifier)
}
func parseRoll(roll string) []string {
// re := regexp.MustCompile(`[+-]?\d*d\d+|[+-]{1}m\d+`)
re := regexp.MustCompile(`[+-]?\d*d\d+`)
return re.FindAllString(roll, -1)
}
// -------
type dice struct {
sides int
}
var random = rand.New(rand.NewSource(time.Now().UnixNano()))
func NewDice(sides int) *dice {
return &dice{sides}
}
func (d *dice) Roll() int {
return random.Intn(d.sides) + 1
}
func (d *dice) Sides() int {
return d.sides
}
// --------
type roll struct {
d *dice
throws int
modifier int
nextRoll *roll
}
// NewRoll creates and returns and empty roll.
func NewRoll() *roll {
return &roll{}
}
func newRollWithDice(die *dice, throws int, modifier int) *roll {
return &roll{die, throws, modifier, nil}
}
func (r *roll) throw() int {
if r.d == nil {
return 0
}
var results int
for i := 0; i < r.throws; i++ {
res := r.d.Roll() * r.modifier
results += res
}
if r.nextRoll == nil {
return results
} else {
return results + r.nextRoll.throw()
}
}
func (r *roll) die(die *dice, throws int, modifier int) *roll {
newRoll := newRollWithDice(die, throws, modifier)
newRoll.nextRoll = r
return newRoll
}