Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Randomly giving item with percentage?

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.

2 comments

0

Could you post the entire script? That would help alot

0

There's no script that needs posting?

1 answer

✓ Accepted answer

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.

1 comment

0

Alright, thanks a lot. Would there be a way to give everything a percentage or would that be too complicated?

This discussion is preserved as it was. New answers, comments, and votes are closed.