采样工具
加权随机 API
Section titled “加权随机 API”WeightedRandom
Section titled “WeightedRandom”预计算累积权重,高效随机选择:
import { createWeightedRandom } from '@esengine/procgen';
const selector = createWeightedRandom([ { value: 'apple', weight: 5 }, { value: 'banana', weight: 3 }, { value: 'cherry', weight: 2 }]);
// 使用种子随机数const result = selector.pick(rng);
// 使用 Math.randomconst result2 = selector.pickRandom();
// 获取概率console.log(selector.getProbability(0)); // 0.5 (5/10)console.log(selector.size); // 3console.log(selector.totalWeight); // 10import { weightedPick, weightedPickFromMap } from '@esengine/procgen';
// 从数组选择const item = weightedPick([ { value: 'a', weight: 1 }, { value: 'b', weight: 2 }], rng);
// 从对象选择const item2 = weightedPickFromMap({ 'common': 60, 'rare': 30, 'epic': 10}, rng);洗牌 API
Section titled “洗牌 API”shuffle / shuffleCopy
Section titled “shuffle / shuffleCopy”Fisher-Yates 洗牌算法:
import { shuffle, shuffleCopy } from '@esengine/procgen';
const arr = [1, 2, 3, 4, 5];
// 原地洗牌shuffle(arr, rng);
// 创建洗牌副本(不修改原数组)const shuffled = shuffleCopy(arr, rng);pickOne
Section titled “pickOne”随机选择一个元素:
import { pickOne } from '@esengine/procgen';
const items = ['a', 'b', 'c', 'd'];const item = pickOne(items, rng);采样 API
Section titled “采样 API”sample / sampleWithReplacement
Section titled “sample / sampleWithReplacement”import { sample, sampleWithReplacement } from '@esengine/procgen';
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// 采样 3 个不重复元素const unique = sample(arr, 3, rng);
// 采样 5 个(可重复)const withRep = sampleWithReplacement(arr, 5, rng);randomIntegers
Section titled “randomIntegers”生成范围内的随机整数数组:
import { randomIntegers } from '@esengine/procgen';
// 从 1-100 中随机选 5 个不重复的数const nums = randomIntegers(1, 100, 5, rng);weightedSample
Section titled “weightedSample”按权重采样(不重复):
import { weightedSample } from '@esengine/procgen';
const items = ['A', 'B', 'C', 'D', 'E'];const weights = [10, 8, 6, 4, 2];
// 按权重选 3 个const selected = weightedSample(items, weights, 3, rng);// 好:创建一次,多次使用const selector = createWeightedRandom(items);for (let i = 0; i < 1000; i++) { selector.pick(rng);}
// 不好:每次都创建for (let i = 0; i < 1000; i++) { weightedPick(items, rng);}