From 5fe5ef3d949f01ad68a3d683d6d69ffecc364fac Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Sat, 7 Sep 2013 15:03:57 -0400 Subject: rewrite roll in Go --- Makefile | 2 ++ roll.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ roll.php | 35 ----------------------------------- 3 files changed, 54 insertions(+), 35 deletions(-) create mode 100644 roll.go delete mode 100644 roll.php diff --git a/Makefile b/Makefile index e505cba..6db00cb 100644 --- a/Makefile +++ b/Makefile @@ -43,6 +43,8 @@ clean: %: %.php install -m755 $< $@ +%: %.go + go build $< -o $@ .gitignore: Makefile printf '%s\n' '*~' $(BINFILES) > $@ diff --git a/roll.go b/roll.go new file mode 100644 index 0000000..1848754 --- /dev/null +++ b/roll.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "math/rand" + "os" + "regexp" + "strconv" + "time" +) + +func usage() { + fmt.Printf("Arguments are in the format []d[+MOD]\n") +} + +func roll(input string) { + parser := regexp.MustCompile("^([0-9]*)d([0-9]+)([+-][0-9]+)?$") + parts := parser.FindStringSubmatch(input) + if len(parts) < 2 { + usage() + return + } + dice, _ := strconv.Atoi(parts[1]) + die_size, _ := strconv.Atoi(parts[2]) + mod := 0 + if len(parts) > 3 { + mod, _ = strconv.Atoi(parts[3]) + } + if dice < 1 { + dice = 1 + } + + total := 0 + for i := 0; i < dice; i++ { + v := rand.Intn(die_size) + 1 + fmt.Printf("%d+", v) + total += v + } + total += mod + fmt.Printf("%d = %d\n", mod, total) +} + +func main() { + rand.Seed(time.Now().UTC().UnixNano()) + if len(os.Args) == 1 { + usage() + } + args := os.Args[1:] + for _, arg := range args { + roll(arg) + } +} diff --git a/roll.php b/roll.php deleted file mode 100644 index c52f762..0000000 --- a/roll.php +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env php -]d[+MOD]\n"; -} - -function roll($input) { - preg_match('/([0-9]*)d([0-9]+)([+-][0-9]+)?/', $input, $matches); - if (sizeof($matches) < 2) { - usage(); - return; - } - $dice = (int)$matches[1]; - $die_size = (int)$matches[2]; - @$mod = (int)$matches[3]; - if ($dice<1) $dice = 1; - - $total = 0; - for ($i=0; $i < $dice; $i++) { - $v = mt_rand(1, $die_size); - echo $v.'+'; - $total += $v; - } - $total += $mod; - echo $mod.' = '.$total."\n"; -} - -if (sizeof($argv) == 1) { - usage(); -} -array_shift($argv); -foreach ($argv as $arg) { - roll($arg); -} -- cgit v1.2.3-2-g168b