You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.1 KiB
46 lines
1.1 KiB
|
3 weeks ago
|
/** 可复现随机数(对战同步 / 回放) */
|
||
|
|
export class SeededRNG {
|
||
|
|
private _state: number;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @param seed 随机种子,默认 Date.now()
|
||
|
|
*/
|
||
|
|
constructor(seed: number = Date.now()) {
|
||
|
|
this._state = seed >>> 0;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** @returns [0, 1) 均匀随机数 */
|
||
|
|
next(): number {
|
||
|
|
this._state = (1664525 * this._state + 1013904223) >>> 0;
|
||
|
|
return this._state / 0x100000000;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @param min 下界(含)
|
||
|
|
* @param max 上界(不含)
|
||
|
|
* @returns 均匀随机浮点数
|
||
|
|
*/
|
||
|
|
range(min: number, max: number): number {
|
||
|
|
return min + this.next() * (max - min);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @param min 下界(含)
|
||
|
|
* @param max 上界(含)
|
||
|
|
* @returns 均匀随机整数
|
||
|
|
*/
|
||
|
|
int(min: number, max: number): number {
|
||
|
|
return Math.floor(this.range(min, max + 1));
|
||
|
|
}
|
||
|
|
|
||
|
|
/** 导出 RNG 内部状态(战斗快照) */
|
||
|
|
getState(): number {
|
||
|
|
return this._state;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** 恢复 RNG 内部状态 */
|
||
|
|
setState(state: number): void {
|
||
|
|
this._state = state >>> 0;
|
||
|
|
}
|
||
|
|
}
|