Skip to content

Commit

Permalink
feat: negative modifiers
Browse files Browse the repository at this point in the history
Fixes #1
  • Loading branch information
bdunn313 committed Nov 13, 2024
1 parent 655f46e commit 0c89d7e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
16 changes: 14 additions & 2 deletions cmd/roll.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"fmt"
"math"
"math/rand"
"regexp"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -93,7 +94,7 @@ func parseDie(die string) (Die, error) {
}
sides, err := strconv.Atoi(parts[1])
if err != nil {
return d, fmt.Errorf("invalid die sides: %s", parts[1])
return d, fmt.Errorf("invalid die sides: %s, error: %v", parts[1], err)
}
d.Count = count
d.Sides = sides
Expand All @@ -103,7 +104,18 @@ func parseDie(die string) (Die, error) {
func parseExpression(expression string) ([]Die, error) {
var dice []Die
var modifier int
for _, die := range strings.Split(expression, "+") {

// Define a regular expression to capture parts of the dice rolls and modifiers
regex := `([+-]?\d*d\d+|[+-]?\d+)`
re := regexp.MustCompile(regex)

// Extract all matches from the string
matches := re.FindAllString(expression, -1)

for _, die := range matches {
die = strings.TrimSpace(die)

// Die expression
if strings.Contains(die, "d") {
d, err := parseDie(die)
if err != nil {
Expand Down
13 changes: 13 additions & 0 deletions cmd/roll_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,16 @@ func TestAddingModifiers(t *testing.T) {
t.Errorf("RollDice(%s) = %d; want %d", input, result.Total, expected)
}
}

func TestNegativeModifier(t *testing.T) {
r := &mockRand{value: 3}
input := "1d6-2"
expected := 2
result, err := RollDice(r, input)
if err != nil {
t.Errorf("RollDice(%s) = %d; want %d", input, result.Total, expected)
}
if result.Total != expected {
t.Errorf("RollDice(%s) = %d; want %d", input, result.Total, expected)
}
}

0 comments on commit 0c89d7e

Please sign in to comment.