网站首页 javascript技术
小游戏->根据权重获取奖品模型
发布时间:2020-04-10 04:42查看次数:2660
小游戏->根据权重获取奖品模型
实现步骤:根据权重数量总和 生成数组 打散数组从新定义位置,后随即取值获得奖励
示例:
var model = [{
name: '一等奖',
key: 'level1',
radio: 5,
},{
name: '二等奖',
key: 'level2',
radio: 10,
},{
name: '三等奖',
key: 'level3',
radio: 30,
},{
name: '参与',
key: 'level4',
radio: 80
}]
计算权重总和为 80 +30 +10 +5 最后数组中有 129个键
实现过程:
function Draw(prizes) {
this.prizes = prizes;
var prizeList = []
prizes.map(function(item){
prizeList.push({
name: item.name,
value: item.key
})
for(var i=0; i< item.radio; i++) {
prizeList.push({
name: item.name,
value: item.key
})
}
});
prizeList = reset(prizeList)
function randomFrom(lowerValue, upperValue) {
return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
};
function reset(arr) {
var eachArr = arr.concat([])
var lastArr = []
function deepEach(deepArr) {
if (deepArr.length) {
var randomIndex = randomFrom(0, eachArr.length - 1)
lastArr.push(eachArr[randomIndex])
eachArr.splice(randomIndex, 1)
deepEach(eachArr)
}
}
deepEach(eachArr)
return lastArr
}
this.getResult = function() {
var random = randomFrom(0, prizeList.length - 1);
return prizeList[random]
}
}
调用方法:
var draw = new Draw(model);
var drawResult = draw.getResult();
console.log(draw,drawResult,"测试一下")
关键字词:javascript##