aboutsummaryrefslogtreecommitdiff
path: root/games/dr.sh
diff options
context:
space:
mode:
authorTom Ryder <tom@sanctum.geek.nz>2017-04-05 20:06:39 +1200
committerTom Ryder <tom@sanctum.geek.nz>2017-04-05 20:46:47 +1200
commitc8ab406749124d2e762ad5cf53963070113afd0f (patch)
tree54c9721a06957ebe7098a211eea803b0230c0f5d /games/dr.sh
parentHandle POSIX correctness in ~/.bash_profile (diff)
downloaddotfiles-c8ab406749124d2e762ad5cf53963070113afd0f.tar.gz
dotfiles-c8ab406749124d2e762ad5cf53963070113afd0f.zip
Apply runtime shebanging to POSIX shell
Diffstat (limited to 'games/dr.sh')
-rw-r--r--games/dr.sh36
1 files changed, 36 insertions, 0 deletions
diff --git a/games/dr.sh b/games/dr.sh
new file mode 100644
index 00000000..e1db163d
--- /dev/null
+++ b/games/dr.sh
@@ -0,0 +1,36 @@
+#!/bin/sh
+# Roll D&D-style dice in a ndn+n formula, e.g. 10d6+2
+
+# Need exactly one argument
+[ "$#" -eq 1 ] || exit 2
+
+# Arcane string chopping
+n=1 a=0
+nd=${1%+*}
+d=${nd#*d}
+[ "${nd%d*}" != "" ] && n=${nd%d*}
+[ "${1#*+}" = "$1" ] || a=${1#*+}
+
+# Check number of roles and addendum make sense
+[ "$((n > 0 && a >= 0))" -eq 1 ] || exit 2
+
+# Check this is a real die you can actually roll
+case $d in
+ 4|6|8|10|12|20) : ;;
+ *) exit 2 ;;
+esac
+
+# Roll the dice the appropriate number of times using rndi(1df)
+i=0 t=0
+while [ "$i" -lt "$n" ] ; do
+ seed=$(rnds)
+ r=$(rndi 1 "$d" "$seed")
+ t=$((t + r))
+ i=$((i + 1))
+done
+
+# Add the addendum
+t=$((t + a))
+
+# Print it
+printf '%u\n' "$t"