91 lines
3.4 KiB
Python
Executable File
91 lines
3.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# dice - roll dice with notation (3d6+2) and a roll history
|
|
# Usage: dice [NOTATION]... [--count N] [--seed N] [--history] [--clear-history]
|
|
# Notation: NdM+K, e.g. 3d6+2, d20, 2d10-1. History lives in
|
|
# ~/.local/share/fileutils/dice-history.txt (last 100 rolls).
|
|
import argparse, os, random, re, sys
|
|
|
|
HIST = os.path.expanduser("~/.local/share/fileutils/dice-history.txt")
|
|
PAT = re.compile(r"^(\d*)d(\d+)([+-]\d+)?$")
|
|
|
|
def parse(spec):
|
|
m = PAT.match(spec.strip().lower())
|
|
if not m:
|
|
raise ValueError(f"bad dice notation {spec!r} (try 3d6+2 or d20)")
|
|
n = int(m.group(1) or 1)
|
|
sides = int(m.group(2))
|
|
mod = int(m.group(3) or 0)
|
|
if n < 1 or n > 100 or sides < 2 or sides > 1000:
|
|
raise ValueError("dice: 1-100 dice, 2-1000 sides")
|
|
return n, sides, mod
|
|
|
|
def roll(spec, rng):
|
|
n, sides, mod = parse(spec)
|
|
dice = [rng.randint(1, sides) for _ in range(n)]
|
|
return dice, sum(dice) + mod, mod
|
|
|
|
def selftest():
|
|
rng = random.Random(7)
|
|
d, total, mod = roll("3d6+2", rng)
|
|
assert len(d) == 3 and all(1 <= x <= 6 for x in d) and total == sum(d) + 2
|
|
d, total, mod = roll("d20", rng)
|
|
assert len(d) == 1 and 1 <= d[0] <= 20
|
|
assert roll("2d6", random.Random(1))[0] == roll("2d6", random.Random(1))[0]
|
|
try:
|
|
parse("banana")
|
|
raise AssertionError("bad notation accepted")
|
|
except ValueError:
|
|
pass
|
|
print("dice selftest: ok (3d6+2, d20, seeded repeatability, bad notation rejected)")
|
|
return 0
|
|
|
|
def log(line):
|
|
try:
|
|
os.makedirs(os.path.dirname(HIST), exist_ok=True)
|
|
lines = open(HIST).read().splitlines() if os.path.exists(HIST) else []
|
|
lines = (lines + [line])[-100:]
|
|
open(HIST, "w").write("\n".join(lines) + "\n")
|
|
except OSError:
|
|
pass
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(prog="dice",
|
|
description="Roll dice with notation (3d6+2) and keep a roll history.")
|
|
p.add_argument("spec", nargs="*", default=["1d20"], help="dice notation, e.g. 3d6+2 d20")
|
|
p.add_argument("--count", type=int, default=1, help="rolls per notation (default 1)")
|
|
p.add_argument("--seed", type=int, help="seed for reproducible rolls")
|
|
p.add_argument("--history", action="store_true", help="show the roll history and exit")
|
|
p.add_argument("--clear-history", action="store_true", help="clear the roll history")
|
|
p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
|
|
a = p.parse_args()
|
|
if a.selftest:
|
|
return selftest()
|
|
if a.clear_history:
|
|
try:
|
|
os.remove(HIST)
|
|
except FileNotFoundError:
|
|
pass
|
|
print("dice history cleared")
|
|
return 0
|
|
if a.history:
|
|
if os.path.exists(HIST):
|
|
print(open(HIST).read(), end="")
|
|
else:
|
|
print("no dice history yet")
|
|
return 0
|
|
rng = random.Random(a.seed) if a.seed is not None else random.SystemRandom()
|
|
for spec in a.spec:
|
|
try:
|
|
for _ in range(a.count):
|
|
dice, total, mod = roll(spec, rng)
|
|
dice_s = "+".join(map(str, dice))
|
|
mod_s = f"{mod:+d}" if mod else ""
|
|
print(f"{spec}: [{dice_s}]{mod_s} = {total}")
|
|
log(f"{spec}: [{dice_s}]{mod_s} = {total}")
|
|
except ValueError as e:
|
|
print(f"dice: {e}", file=sys.stderr); return 2
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|