How do i make a chance system?

Hey, I’ve been interested in this for a while so I did some research and found a solution I really like, and I hope it helps

It’s weight based, not percentage based

-- your list of items, I tend to have these in a seperate module
local items = {
	{Name = "Iron Sword"},
	{Name = "Iron"},
	{Name = "Gold"}
}

--[[ 
	a loot table, it's wise to keep these seperate from your item list as it allows you to make
	multiple loot tables
	
	needs to be linear, greatest to least, and remember it's based on weight not percentages
--]]
local lootTable = {
	{Item = items[2], Weight = 100}, -- each one of these is an entry
	{Item = items[3], Weight = 50},
	{Item = items[1], Weight = 20}
}

-- used in weight random number generation
local function returnSumOfWeight(lootTable)
	local sum = 0
	for _, entry in ipairs(lootTable) do
		sum = sum + entry.Weight
	end
	return sum
end

-- returns a random item from given lootTable
local function getRandomItem(lootTable)
	-- returns a random number based on total weight of given lootTable
	local randomNumber = math.random(returnSumOfWeight(lootTable))
	
	for _, entry in ipairs(lootTable) do
		if  randomNumber <= entry.Weight then
			return entry.Item
		else
			randomNumber = randomNumber - entry.Weight
		end
	end
end

-- just for testing, mess around with it how you like
for i = 1, 100 do
	local item = getRandomItem(lootTable)
	print(item.Name)
end
Output Examples

when iron is 1000 weight

image

when it’s 100 (closer to the other weights so more even results but iron is still most common)

bonus minecraft example because why not

I did research for a while but found this most helpful

it’s in C# but he does some explaining in english so it will help out in the understanding of a weighted system (I don’t know C# myself, that’s why I can vouch)

46 Likes