1
0
Fork 0

Proxy random methods to component

This commit is contained in:
Pabloader 2026-05-08 15:53:08 +00:00
parent a571d6cc2a
commit 2ac6e37666
1 changed files with 34 additions and 4 deletions

View File

@ -1,19 +1,49 @@
import { type RNGState, SeededRandom } from "@common/random"; import { type NameOptions, type RNGState, SeededRandom } from "@common/random";
import { Component, World } from "../core/world"; import { Component, World } from "../core/world";
import { component } from "../utils/decorators"; import { component } from "../utils/decorators";
@component @component
export class Random extends Component<{ random: RNGState }> { export class Random extends Component<{ random: RNGState }> implements Omit<SeededRandom, 'jump' | 'longJump' | 'fork' | 'toJSON' | 'getState' | 'setState'> {
private rng?: SeededRandom; private rng?: SeededRandom;
constructor(random: SeededRandom | string | number | RNGState = Date.now()) { constructor(random: SeededRandom | string | number | RNGState = Date.now()) {
super({ super({
random: (() => { random: (() => {
this.rng = random instanceof SeededRandom ? random : new SeededRandom(random); const rng = random instanceof SeededRandom ? random : new SeededRandom(random);
return this.rng.getState(); return rng.getState();
})() })()
}); });
} }
nextFloat(): number {
return this.use((rng) => rng.nextFloat());
}
nextInt(min: number, max: number): number;
nextInt(max: number): number;
nextInt(minOrMax: number, max?: number): number {
return this.use((rng) => rng.nextInt(minOrMax, max as number));
}
nextBool(): boolean {
return this.use((rng) => rng.nextBool());
}
nextName(options?: NameOptions): string {
return this.use((rng) => rng.nextName(options));
}
choice<T>(iterable: Iterable<T>): T;
choice<T>(iterable: Iterable<T>, k: number): T[];
choice<T>(iterable: Iterable<T>, k?: number): T | T[] {
return this.use((rng) => rng.choice(iterable, k as number));
}
weightedChoice<T>(items: readonly T[], weights: readonly number[]): T;
weightedChoice<T>(items: readonly T[], weights: readonly number[], k: number): T[];
weightedChoice<T>(items: readonly T[], weights: readonly number[], k?: number): T | T[] {
return this.use((rng) => rng.weightedChoice(items, weights, k as number));
}
shuffle<T>(arr: T[]): T[] {
return this.use((rng) => rng.shuffle(arr));
}
toShuffled<T>(arr: readonly T[]): T[] {
return this.use((rng) => rng.toShuffled(arr));
}
use<T>(fn: (rng: SeededRandom) => T): T { use<T>(fn: (rng: SeededRandom) => T): T {
if (this.rng) { if (this.rng) {