Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions dice_roller/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package main

import (
"fmt"
"math/rand"
"regexp"
"strconv"
"time"
)

func main() {
// Regular expression to validate input format (XdY[+-]N)
diceExpr := regexp.MustCompile(`^(\d+)d(\d+)([+-]\d+)?$`)

fmt.Println("Enter dice expression (XdY[+-]N): ")
var input string
fmt.Scanln(&input)

// Validate input format
if !diceExpr.MatchString(input) {
fmt.Println("Invalid input format. Please enter XdY[+-]N where X is the number of dice, Y is the number of sides, and N is the optional modifier.")
return
}

// Extract number of dice, sides, and modifier (if present) from input
matches := diceExpr.FindStringSubmatch(input)
numDice, _ := strconv.Atoi(matches[1])
numSides, _ := strconv.Atoi(matches[2])
modifier := 0
if len(matches) > 3 {
modifier, _ = strconv.Atoi(matches[3])
}

// Seed random number generator
rand.Seed(int64(time.Now().UnixNano()))

// Roll dice and sum results
var total int
for i := 0; i < numDice; i++ {
roll := rand.Intn(numSides) + 1
fmt.Printf("Die %d: %d\n", i+1, roll)
total += roll
}

// Apply modifier and print total
total += modifier
fmt.Printf("Total: %d (including modifier of %d)\n", total, modifier)
}
46 changes: 46 additions & 0 deletions dice_roller/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package main
//Start of Elios attempt
import (
"io/ioutil"
"os"
"strconv"
"strings"
"testing"
)

func TestRollDice(t *testing.T) {
tests := []struct {
input string
expected int
}{
{"2d6", 7}, // Simple roll
{"1d20+5", 18}, // Roll with modifier
{"4d4-2", 9}, // Multiple dice with modifier
}

for _, test := range tests {
// Capture standard output to compare results
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w

// Call the main function with the test input
main()

// Restore standard output
w.Close()
os.Stdout = old

// Read the captured output
output, _ := ioutil.ReadAll(r)
resultLine := strings.Split(string(output), "\n")[len(strings.Split(string(output), "\n"))-1]
splitResult := strings.Split(resultLine, ": ")
if len(splitResult) >= 2 {
actual, _ := strconv.Atoi(splitResult[1])
// Use actual here
if actual != test.expected {
t.Errorf("Roll failed for input %s: expected %d, got %d", test.input, test.expected, actual)
}
}
}
}