PT
games/rob-revisited / src / Revisited / Land / Rng.php · commit f9a1307
<?phpnamespace App\Revisited\Land;/** * A small seeded random generator (Park-Miller, computed in floats: exact and the same on 32-bit WebAssembly PHP * and 64-bit desktop PHP). Never touches mt_rand's global state. */final class Rng{    private float $s;    public function __construct(int $seed)    {        $s = fmod(abs((float) $seed) * 7919.0 + 12345.0, 2147483646.0);        $this->s = $s < 1 ? 1.0 : $s;        $this->next();        $this->next();    }    /** 0 <= x < 1 */    public function next(): float    {        $this->s = fmod($this->s * 16807.0, 2147483647.0);        return ($this->s - 1) / 2147483646.0;    }    public function range(float $min, float $max): float    {        return $min + ($max - $min) * $this->next();    }    public function int(int $min, int $max): int    {        return $min + (int) floor($this->next() * ($max - $min + 1) - 1e-9);    }    public function chance(float $p): bool    {        return $this->next() < $p;    }    /**     * @template T     * @param list<T> $list     * @return T     */    public function pick(array $list): mixed    {        return $list[$this->int(0, count($list) - 1)];    }    public function state(): float    {        return $this->s;    }    public function setState(float $s): void    {        $this->s = $s >= 1 ? $s : 1.0;    }}