创造一个稀有的机会。在 javascript 中

我想知道如何在 js 中创造难得的机会?使用数学函数。


假设有 1% 的机会得到帽子之类的东西。


我如何让它有 1% 的机会?如果我想投入 50% 我该怎么做?


我试着用这个


var gen = Math.floor(Math.random() * 100);

    var type = common;

      if(gen > 59) type = common;

      //if(gen < 16) type = alolans

      //if(gen < 10) type = galarians

      if(gen < 8) type = mythics;

      if(gen < 3) type = legends;

      if(gen < 2) type = ub; 

不起作用请帮忙。在代码中,我已经输入了所有的机会数字,如何让它工作并且很少得到它?


长风秋雁
浏览 145回答 3
3回答

RISEBY

你可以试试这种方法,在代码中注释。只需确保机会的总和低于 100,然后将 0 放入其中,以填补剩余的机会。与其他方法相比,这使您可以轻松添加/删除稀有度或更改机会,而无需触及所有其他值。如果您想以 8% 的几率再添加一个,只需在数组上添加{type: 'oneMore', chance: 8}工作完成了,一切仍然有效:)var rarities = [{&nbsp; type: "common",&nbsp; chance: 0}, {&nbsp; type: "mythics",&nbsp; chance: 35}, {&nbsp; type: "legends",&nbsp; chance: 20}, {&nbsp; type: "ub",&nbsp; chance: 1}];function pickRandom() {&nbsp; // Calculate chances for common&nbsp; var filler = 100 - rarities.map(r => r.chance).reduce((sum, current) => sum + current);&nbsp; if (filler <= 0) {&nbsp; &nbsp; console.log("chances sum is higher than 100!");&nbsp; &nbsp; return;&nbsp; }&nbsp; // Create an array of 100 elements, based on the chances field&nbsp; var probability = rarities.map((r, i) => Array(r.chance === 0 ? filler : r.chance).fill(i)).reduce((c, v) => c.concat(v), []);&nbsp; // Pick one&nbsp; var pIndex = Math.floor(Math.random() * 100);&nbsp; var rarity = rarities[probability[pIndex]];&nbsp; console.log(rarity.type);}pickRandom();pickRandom();pickRandom();pickRandom();pickRandom();pickRandom();

POPMUISE

您需要总结获得选择类型的正确值的机会。function getType() {&nbsp; &nbsp; var gen = Math.floor(Math.random() * 100);&nbsp; &nbsp; console.log(gen);&nbsp; &nbsp; if (gen < 2) return 'ub';&nbsp; &nbsp; if (gen < 5) return 'legends';&nbsp; &nbsp; if (gen < 13) return 'mythics';&nbsp; &nbsp; if (gen < 23) return 'galarians';&nbsp; &nbsp; if (gen < 39) return 'alolans';&nbsp; &nbsp; return 'common';}console.log(getType());

侃侃无极

试试这个代码:var gen = Math.floor(Math.random() * 100);var type = common;&nbsp; if(gen > 59) type = common;&nbsp; else if(gen < 2) type = ub;&nbsp; else if(gen < 3) type = legends;&nbsp; else if(gen < 8) type = mythics;以较低的开始 if statstatment (<)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript