亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

創造一個稀有的機會。在 javascript 中

創造一個稀有的機會。在 javascript 中

長風秋雁 2022-10-08 18:04:07
我想知道如何在 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; 不起作用請幫忙。在代碼中,我已經輸入了所有的機會數字,如何讓它工作并且很少得到它?
查看完整描述

3 回答

?
RISEBY

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();


查看完整回答
反對 回復 2022-10-08
?
POPMUISE

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());


查看完整回答
反對 回復 2022-10-08
?
侃侃無極

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 (<)


查看完整回答
反對 回復 2022-10-08
  • 3 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號