Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Randomly giving item with percentage?

Asked by
iFlusters 355 Moderation Voter
8 years ago

Please don't take this as a request!

I was wondering how I could create possible a table for example:

local Common = {
CommonAxe = blah.blah
}

local Rare = {
RareAxe = blah.blah
}

I have a chest which when opens will give the items, I have no problem giving the item, it's just how. Of course I can simply clone the item from a place to their inventory, but how would I add a percentage (rarity) to the item so they have less of a chance of getting it? I'm guessing this would involve

math.random()

Please, again, this is not a request, just a few lines of code would really help out.

0
Could you post the entire script? That would help alot TheHospitalDev 1134 — 8y
0
There's no script that needs posting? iFlusters 355 — 8y

1 answer

Log in to vote
3
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
8 years ago

If you have a probability decided of something being chosen from the rare set, you can have

local Common={"CommonAxe",CommonAxe=blah.blah}
local Rare={"RareAxe",RareAxe=blah.blah}
local rarity=1/5 -- 1 in 5

local itemset=math.random()<rarity and Rare or Common
local item=itemset[itemset[math.random(#itemset)]]

where the rare set is chosen by chance and something random is chosen out of the chosen set.

If you want each item to have its own chance/weight of being chosen, you can do this:

local items={
    {w=4,item=CommonAxe},
    {w=1,item=RareAxe}
}
local wsum=0
for i=1,#items do wsum=wsum+items[i].w end

function chooseItem()
    local itemn=math.random(wsum)
    local n=0
    for i=1,#items do
        n=n+items[i].w
        if n>=itemn then
            return items[i].item
        end
    end
end

A random number is chosen from the sum of weights of items, and the weights are added in order until the sum reaches the random number chosen. The weight landed on corresponds to the returned item.

0
Alright, thanks a lot. Would there be a way to give everything a percentage or would that be too complicated? iFlusters 355 — 8y
Ad

Answer this question