class_name Rng ## Seeded Mulberry32 (rng.ts). The state is a Dictionary `{s}` kept in the GameState, so a cloned ## state carries its RNG along, which keeps every game reproducible from its seed. ## ## GDScript ints are 64-bit, so every step is masked to 32 bits to match JS's Math.imul and `>>> 0`. const M := 0xFFFFFFFF static func make(seed: int) -> Dictionary: return {"s": seed & M} ## The low 32 bits of a * b, for a and b in 0..2^32 - 1, without overflowing 64 bits. static func _imul(a: int, b: int) -> int: return ((a & 0xFFFF) * b + ((((a >> 16) * b) & 0xFFFF) << 16)) & M static func next_float(r: Dictionary) -> float: r.s = (r.s + 0x6d2b79f5) & M var t: int = r.s t = _imul(t ^ (t >> 15), t | 1) t = t ^ ((t + _imul(t ^ (t >> 7), t | 61)) & M) return float((t ^ (t >> 14)) & M) / 4294967296.0 static func rand_int(r: Dictionary, n: int) -> int: return floori(next_float(r) * n) static func d6(r: Dictionary) -> int: return 1 + rand_int(r, 6) static func pick(r: Dictionary, items: Array) -> Variant: return items[rand_int(r, items.size())] ## Shuffles `items` in place (Fisher–Yates, as in TS) and returns it. static func shuffle(r: Dictionary, items: Array) -> Array: var i := items.size() - 1 while i > 0: var j := rand_int(r, i + 1) var tmp = items[i] items[i] = items[j] items[j] = tmp i -= 1 return items