2 回答
TA贡献1804条经验 获得超3个赞
您所追求的称为加权随机选择,也就是说它仍然是随机选择,但有些项目的权重更高。该算法相当简单。
您从一个项目列表开始,并为每个项目分配一个相对权重。权重越高,被采摘的可能性就越大。然后,在 0 和所有项目的总重量之间选择一个随机数,然后逐步检查项目,从您选择的随机数中减去每个项目的重量。当数字达到零时,您就有了您的物品。
这是一个例子。
function WeightedBroker(){
this.totalWeight = 0;
this.items = [];
this.addItem = function(value,weight){
this.items.push({value,weight});
this.totalWeight+= weight;
}
this.pickItem = function(){
var rnd = Math.floor(Math.random() * this.totalWeight);
for(var i=0;i<this.items.length;i++){
if(rnd<=this.items[i].weight)
return this.items[i].value;
rnd -= this.items[i].weight;
}
}
}
var broker = new WeightedBroker();
broker.addItem("a",100);
broker.addItem("b",10);
broker.addItem("c",1);
for(var i=0;i<10;i++)
console.log(broker.pickItem());
将此应用于您的代码非常简单,您需要将这 2 个数组(一个带有 img html,一个带有名称)更改为包含属性name和src. 您可以根据您的要求将这些项目中的每一个添加到我上面写的代理中,并为每个项目添加适当的权重。像这样的东西:
function WeightedBroker(){
this.totalWeight = 0;
this.items = [];
this.addItem = function(value,weight){
this.items.push({value,weight});
this.totalWeight+= weight;
}
this.pickItem = function(){
var rnd = Math.floor(Math.random() * this.totalWeight);
for(var i=0;i<this.items.length;i++){
if(rnd<=this.items[i].weight)
return this.items[i].value;
rnd -= this.items[i].weight;
}
}
}
var broker = new WeightedBroker();
broker.addItem({src:"<img src = 'http://www.homastudio.com/img/spongebob.png'>",name:"Spongebob Squarepants"},100);
broker.addItem({src:"<img src = 'http://www.homastudio.com/img/patrick.png'>",name:"Patrick Star"},100);
broker.addItem({src:"<img src = 'http://www.homastudio.com/img/squidward.png'>",name:"Squidward Tentacles"},100);
broker.addItem({src:"<img src = 'http://www.homastudio.com/img/sandy.png'>",name:"Sandy Cheeks"},100);
broker.addItem({src:"<img src = 'http://www.homastudio.com/img/krabs.png'>",name:"Eugene Krabs"},100);
broker.addItem({src:"<img src = 'http://www.homastudio.com/img/larry.png'>",name:"Larry Lobster"},100);
var item = broker.pickItem();
document.getElementById("pic").innerHTML=item.src;
document.getElementById("name").innerHTML=item.name;
<div id="name"></div>
<div id="pic"></div>
TA贡献2021条经验 获得超8个赞
而不是让数组只让图像执行以下操作(其中“稀有”中的低数字意味着更稀有:
var spongebob = {
url:"<img src = 'http://www.homastudio.com/img/spongebob.png'>",
rarity: 1
};
var patrick = {
url:"<img src = 'http://www.homastudio.com/img/patrick.png'>",
rarity: 2
};
var squidward = {
url:"<img src = 'http://www.homastudio.com/img/squidward.png'>",
rarity: 4
};
var images = [spongebob, patrick, squidward];
var imageChoiceArr = [];
for(var i=0;i<images.length;i++) {
image = images[i];
for(var ii=0;ii<image.rarity;ii++) {
imageChoiceArr.push(image.url);
}
}
然后从“imageChoiceArr”中随机选择
添加回答
举报