summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLuke Shumaker <LukeShu@sbcglobal.net>2013-09-07 15:03:57 -0400
committerLuke Shumaker <LukeShu@sbcglobal.net>2013-09-07 15:03:57 -0400
commit5fe5ef3d949f01ad68a3d683d6d69ffecc364fac (patch)
tree579a699d6794ad200be01113251cd07c23d6868a
parent23ebdbace364ffc2e27403e103594c12c0002b5b (diff)
rewrite roll in Go
-rw-r--r--Makefile2
-rw-r--r--roll.go52
-rw-r--r--roll.php35
3 files changed, 54 insertions, 35 deletions
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 [<COUNT>]d<SIZE>[+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
-<?php
-
-function usage() {
- echo "Arguments are in the format [<COUNT>]d<SIZE>[+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);
-}