62 lines
1.8 KiB
GDScript
62 lines
1.8 KiB
GDScript
class_name Odds
|
|
## Dice odds (odds.ts): the exact distribution of a sum of d6, and combat chances from it.
|
|
|
|
static var _cache := {}
|
|
static var _roll_cache := {}
|
|
|
|
|
|
## Distribution of the sum of n d6, as probability by total.
|
|
static func _sum_distribution(n: int) -> Dictionary:
|
|
var dist := {0: 1.0}
|
|
for i in n:
|
|
var next := {}
|
|
for total in dist:
|
|
for face in range(1, 7):
|
|
next[total + face] = next.get(total + face, 0.0) + dist[total] / 6.0
|
|
dist = next
|
|
return dist
|
|
|
|
|
|
## Exact chance that `atk` Cores beat `def` Cores, with ties rerolled.
|
|
static func win_chance(atk: int, def: int) -> float:
|
|
var key := "%d:%d" % [atk, def]
|
|
if _cache.has(key):
|
|
return _cache[key]
|
|
var win := 0.0
|
|
var lose := 0.0
|
|
var a := _sum_distribution(maxi(1, atk))
|
|
var d := _sum_distribution(maxi(1, def))
|
|
for sa in a:
|
|
for sd in d:
|
|
if sa > sd:
|
|
win += a[sa] * d[sd]
|
|
elif sa < sd:
|
|
lose += a[sa] * d[sd]
|
|
var chance := win / (win + lose)
|
|
_cache[key] = chance
|
|
return chance
|
|
|
|
|
|
## One roll of `atk` Cores against `def` Cores: {win, tie, lose} chances (no rerolls), and the
|
|
## expected damage to the defenders (damageDealt) and to the attacker (damageTaken) under the health
|
|
## rule, where the margin is the damage.
|
|
static func roll_odds(atk: int, def: int) -> Dictionary:
|
|
var key := "%d:%d" % [atk, def]
|
|
if _roll_cache.has(key):
|
|
return _roll_cache[key]
|
|
var out := {"win": 0.0, "tie": 0.0, "lose": 0.0, "damageDealt": 0.0, "damageTaken": 0.0}
|
|
var a := _sum_distribution(maxi(1, atk))
|
|
var d := _sum_distribution(maxi(1, def))
|
|
for sa in a:
|
|
for sd in d:
|
|
var p: float = a[sa] * d[sd]
|
|
if sa > sd:
|
|
out.win += p
|
|
out.damageDealt += p * (sa - sd)
|
|
elif sa < sd:
|
|
out.lose += p
|
|
out.damageTaken += p * (sd - sa)
|
|
else:
|
|
out.tie += p
|
|
_roll_cache[key] = out
|
|
return out
|