例如,我在一个数组中有 3 个元素:

public function randomTile():Number

{

var tiles:Array = new Array(fire,ice,water);

var index:Number=Math.floor(Math.random()*tiles.length);

return tiles[index];

}

火(70%)、冰(10%)、水(20%)的出现几率怎么设置?

最佳答案

这应该适用于任意数量的元素,您可以指定任何机会值。

var tiles:Array = [
  {"item":"fire", "chance":70 },
  {"item":"ice",  "chance":10 },
  {"item":"water","chance":20}
];

var picked:Object = pickRandomByChance(tiles);
trace(picked.item);

public function pickRandomByChance(options:Array):Object
{
  var copy:Array = [];
  var range:Number = 0;
  for (var i:int = 0; i < options.length; i++)
  {
    copy.push( { "item":options[i].item, "chance":options[i].chance } );
    range += copy[i].chance;
    if (i > 0)
      copy[i].chance += copy[i - 1].chance;
  }

  var pick:Number = Math.floor(Math.random() * range);

  for (i = 0; i < copy.length; i++)
  {
    if (pick <= copy[i].chance)
      return copy[i];
  }
  return null;
}

关于actionscript-3 - 设置数组中元素出现的机会,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12114189/

10-13 04:12