3 回答

TA貢獻1856條經驗 獲得超5個贊
你可以試試這種方法,在代碼中注釋。
只需確保機會的總和低于 100,然后將 0 放入其中,以填補剩余的機會。
與其他方法相比,這使您可以輕松添加/刪除稀有度或更改機會,而無需觸及所有其他值。
如果您想以 8% 的幾率再添加一個,只需在數組上添加
{type: 'oneMore', chance: 8}
工作完成了,一切仍然有效:)
var rarities = [{
type: "common",
chance: 0
}, {
type: "mythics",
chance: 35
}, {
type: "legends",
chance: 20
}, {
type: "ub",
chance: 1
}];
function pickRandom() {
// Calculate chances for common
var filler = 100 - rarities.map(r => r.chance).reduce((sum, current) => sum + current);
if (filler <= 0) {
console.log("chances sum is higher than 100!");
return;
}
// Create an array of 100 elements, based on the chances field
var probability = rarities.map((r, i) => Array(r.chance === 0 ? filler : r.chance).fill(i)).reduce((c, v) => c.concat(v), []);
// Pick one
var pIndex = Math.floor(Math.random() * 100);
var rarity = rarities[probability[pIndex]];
console.log(rarity.type);
}
pickRandom();
pickRandom();
pickRandom();
pickRandom();
pickRandom();
pickRandom();

TA貢獻1765條經驗 獲得超5個贊
您需要總結獲得選擇類型的正確值的機會。
function getType() {
var gen = Math.floor(Math.random() * 100);
console.log(gen);
if (gen < 2) return 'ub';
if (gen < 5) return 'legends';
if (gen < 13) return 'mythics';
if (gen < 23) return 'galarians';
if (gen < 39) return 'alolans';
return 'common';
}
console.log(getType());

TA貢獻2051條經驗 獲得超10個贊
試試這個代碼:
var gen = Math.floor(Math.random() * 100);
var type = common;
if(gen > 59) type = common;
else if(gen < 2) type = ub;
else if(gen < 3) type = legends;
else if(gen < 8) type = mythics;
以較低的開始 if statstatment (<)
添加回答
舉報