我有一系列对象代表我正在努力开发的游戏中的生物.这些对象具有(以及其他)唯一标识符和产生的权重(或概率).
我正在尝试开发一种随机生成生物的算法,但我没有想出一种使用权重的方法(我真的不知道该怎么做).
有人可以帮忙吗?
生物数组的一个例子可能是:
var creatures = [
{id: 1, weight: 25},
{id: 2, weight: 15},
{id: 3, weight: 5},
{id: 4, weight: 45},
{id: 5, weight: 10}
]
Run Code Online (Sandbox Code Playgroud)
我发现在这个博客中用PHP实现了这个很好的算法,我认为migth适合你的需求.
我刚把它收养到了JS.
var creatures = [{
id: 1,
weight: 25
}, {
id: 2,
weight: 15
}, {
id: 3,
weight: 5
}, {
id: 4,
weight: 45
}, {
id: 5,
weight: 10
}],
sumOfWeights = creatures.reduce(function(memo, creature) {
return memo + creature.weight;
}, 0),
selectedWeigths = {};
function getRandom(sumOfWeights) {
var random = Math.floor(Math.random() * (sumOfWeights + 1));
return function(creature) {
random -= creature.weight;
return random <= 0;
};
}
for (var i = 0; i < 1000; i++) {
var creature = creatures.find(getRandom(sumOfWeights));
selectedWeigths[creature.weight] = (selectedWeigths[creature.weight] || 0) + 1;
}
console.log(selectedWeigths);Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.