Chest randomiser system

  • What does the code do and what are you not satisfied with?
    This code is a more developed version of your average chest randomiser, picking a random amount of a rarity of an object based on several ‘inputs’ as seen in the chances table. I am currently satisfied with it but would like to know any efficiency flaws.
  • How (specifically) do you want to improve the code?
    I would like to know any ways I can make the process faster / more efficient.
local CardList = {
['Common'] = {'Common1', 'Common2'},
['Rare'] = {'Rare1', 'Rare2'},
['Epic'] = {'Epic1', 'Epic2'},
['Legendary'] = {'Legendary1', 'Legendary2'},
}

local Chests = {
	['TestChest'] = {
		Rolls = {Min = 6, Max = 8},
		Cost = 10,
		Chances = {
			Common = {Weight = 50, Min = 50, Max = 100},
			Rare = {Weight = 30, Min = 20, Max = 40},
			Epic = {Weight = 15, Min = 5, Max = 10, Cap = 20},
			Legendary = {Weight = 5, Min = 1, Max = 1, Cap = 1}
		
		}
	}
}

function GetTotalWeight(Table)
	local Weight = 0
	for i,v in pairs(Table) do
		Weight = Weight + v.Weight
	end
	return Weight
end


function OpenChest(Player, ChestName)
	local ChestData = Chests[ChestName]
	local Rolls = math.random(ChestData.Rolls['Min'], ChestData.Rolls['Max'])
	
	local Collected = {}
	local Counts = {['Common'] = 0, ['Rare'] = 0, ['Epic'] = 0, ['Legendary'] = 0}
	
	local TotalWeight = GetTotalWeight(ChestData.Chances)
	
	for _ = 1, Rolls do
		local Weight = math.random(1, TotalWeight)
		local Count = 0
		for i,v in pairs(ChestData.Chances) do
			Count = Count + v.Weight
			if Count >= Weight then
				local List = CardList[i]
				local Card = List[math.random(1, #List)]
				
				local Amount = math.random(v.Min, v.Max)
				
				if Collected[Card] then
					Collected[Card] = Collected[Card] + Amount
				else
					Collected[Card] = Amount
				end
				
				Counts[i] = Counts[i] + Amount
				
				if ChestData.Chances[i].Cap then
					if Counts[i] >= ChestData.Chances[i].Cap then
						TotalWeight = TotalWeight - ChestData.Chances[i].Weight
						ChestData.Chances[i] = nil
					end
				end
			end
		end
	end
end
3 Likes