TableTower/core/dice.gd
2026-11-10 21:19:36 -06:00

131 lines
3.4 KiB
GDScript

class_name Dice
extends RefCounted
## A dice expression such as "1d100", "2d6" or "1d8+2".
##
## Parse with Dice.parse(); check `valid` before use. Invalid expressions never
## roll and have min/max of 0.
const MAX_COUNT := 20
const MAX_SIDES := 1000
const MAX_BONUS := 9999
var valid: bool = false
var count: int = 1
var sides: int = 100
var bonus: int = 0
var _dist: Dictionary = {}
## Parses "NdM", "dM", "NdM+K" or "NdM-K". Spaces and case are ignored.
static func parse(text: String) -> Dice:
var rx := RegEx.new()
rx.compile("^(\\d*)d(\\d+)([+-]\\d+)?$")
var m := rx.search(text.strip_edges().to_lower().replace(" ", ""))
if m == null:
var bad := Dice.new()
return bad
var n: int = m.get_string(1).to_int() if m.get_string(1) != "" else 1
var k: int = m.get_string(3).to_int() if m.get_string(3) != "" else 0
return Dice.make(n, m.get_string(2).to_int(), k)
static func make(p_count: int, p_sides: int, p_bonus: int = 0) -> Dice:
var d := Dice.new()
d.count = p_count
d.sides = p_sides
d.bonus = p_bonus
d.valid = p_count >= 1 and p_count <= MAX_COUNT and p_sides >= 2 and p_sides <= MAX_SIDES and absi(p_bonus) <= MAX_BONUS
return d
static func is_valid_text(text: String) -> bool:
return parse(text).valid
## "" when `text` is something to roll instead of a card's dice: plain dice
## ("3d10+70"), or a rule that rolls at least one die ("2d6 + @luck").
## Otherwise a plain-words reason.
static func roll_problem(text: String) -> String:
var s := text.strip_edges()
if s == "" or parse(s).valid:
return ""
var err := Expr.check(s)
if err != "":
return err
if RegEx.create_from_string("(?i)(^|[^a-z0-9_@])\\d*d\\d*([^a-z0-9_]|$)").search(s) == null:
return "it doesn't roll any dice"
return ""
func min_value() -> int:
return count + bonus if valid else 0
func max_value() -> int:
return count * sides + bonus if valid else 0
## Normalized expression, e.g. "1d100", "2d6", "1d8+2".
func expression() -> String:
var s := "%dd%d" % [count, sides]
if bonus > 0:
s += "+%d" % bonus
elif bonus < 0:
s += str(bonus)
return s
## Short label: "d100" for a single die with no bonus, otherwise the expression.
func label() -> String:
return "d%d" % sides if count == 1 and bonus == 0 else expression()
## True only for exactly 1d100.
func is_d100() -> bool:
return valid and count == 1 and sides == 100 and bonus == 0
func roll(rng: RandomNumberGenerator) -> int:
if not valid:
return 0
var total := bonus
for i in count:
total += rng.randi_range(1, sides)
return total
## Exact probability of every total: value -> probability (sums to 1).
func distribution() -> Dictionary:
if not valid:
return {}
if not _dist.is_empty():
return _dist
# cur[i] = probability of total (count_so_far + i); each die is a sliding-window sum.
var cur := PackedFloat64Array([1.0])
var face := 1.0 / float(sides)
for k in count:
var next := PackedFloat64Array()
next.resize(cur.size() + sides - 1)
var run := 0.0
for i in next.size():
if i < cur.size():
run += cur[i]
if i >= sides:
run -= cur[i - sides]
next[i] = run * face
cur = next
var lo := count + bonus
for i in cur.size():
_dist[lo + i] = cur[i]
return _dist
## Probability that the total falls within lo..hi inclusive.
func probability_between(lo: int, hi: int) -> float:
var sum := 0.0
var dist := distribution()
for v: int in dist:
if v >= lo and v <= hi:
sum += float(dist[v])
return sum