Quick Links: Download Gideros Studio | Gideros Documentation | Gideros Development Center | Gideros community chat | DONATE
percentages — Gideros Forum

percentages

AbizAbiz Member
edited December 2011 in Game & application design
Hello,
can anyone tell me the best way to randomize something with their being a percentage of it weighted on a side?
for example my game is to shoot some zombies, and i want their being a 40/30/20/10% chance of it spawning a certain type of zombie, here is the code that i have now

local percentage = math.random ( 0, 100 )
if percentage <=40 then
-- spawn weak zombie
else if percentage >40 or percentage <=70 then
-- spawn regular zombie
else if percentage >70 or percentage <=90 then
-- spawn fast zombie
else if percentage >90 then
-- spawn brutal zombie
end

is this the best way to do it?

Comments

  • atilimatilim Maintainer
    edited December 2011
    Hi Abiz,

    IMHO, your way is pretty good and can be improved a little bit:
    local percentage = math.random(0, 100)
    if percentage <= 40 then
    -- spawn weak zombie
    elseif percentage <= 70 then
    -- spawn regular zombie
    elseif percentage <= 90 then
    -- spawn fast zombie
    else
    -- spawn brutal zombie
    end
    If you want to generalize this approach, you may use a way like this. Here spawnWeakZombie, spawnRegularZombie, spawnFastZombie and spawnBrutalZombie are functions:
    local spawnList = {
      {ratio = 0.4, func = spawnWeakZombie},
      {ratio = 0.3, func = spawnRegularZombie},
      {ratio = 0.2, func = spawnFastZombie},
      {ratio = 0.1, func = spawnBrutalZombie},
    }
     
    local function spawnZombie()
      local rnd = math.random()
      local sum = 0
      for i = 1, #spawnList do
        sum = sum + spawnList[i].ratio
        if rnd <= sum then
          spawnList[i].func()
          return
        end
      end
    end

    hmmmhh.. zoombiieesss.. :)

    Likes: MikeHart

    +1 -1 (+1 / -0 )Share on Facebook
Sign In or Register to comment.