This is the current code I have as my randomizer. Based on the results it seems to be doing alright. I just wanted to see if someone could double check or maybe make an alteration that could make it better:
local BoxOne = {
{name = "Common", rarity = 40, xp = math.random(5,10)},
{name = "Uncommon", rarity = 30, xp = math.random(15,25)},
{name = "Rare", rarity = 15, xp = math.random(75,200)},
{name = "Insane", rarity = 10, xp = math.random(300,800)},
{name = "Legendary", rarity = 4, xp = math.random(1000,1200)},
{name = "Godlike", rarity = 1, xp = math.random(1500,2500)},
}
local function selectRandomItem()
local totalRarity = 0
for _, item in ipairs(BoxOne) do
totalRarity = totalRarity + item.rarity
end
local randomValue = math.random() * totalRarity
local cumulativeRarity = 0
for _, item in ipairs(BoxOne) do
cumulativeRarity = cumulativeRarity + item.rarity
if randomValue <= cumulativeRarity then
return item
end
end
end
local playerItem = selectRandomItem()
Having math.random() in the table there means that the random xp number will generate once when the server is first started and never change after that for each server.
I would instead recommend lowerBound and upperBound variables, and in the function you can put xp = math.random(lowerBound, upperBound)
Your randomizer code looks functionally sound for a basic random selection based on rarity weights. Howeeawver, there’s one significant issue regarding the way you’re generating the xp for eeaach item. The way it’s currently set up, the xp value is determined once when the BoxOne table is initialized, and it remains the same for each item every time it’s selectead. If you want the xp to be randomly determined each time an item is selectede, you need to generate it within the selectRandomItem function.
Here’s like a zupdated version of your code
local BoxOne = {
{name = "Common", rarity = 40},
{name = "Uncommon", rarity = 30},
{name = "Rare", rarity = 15},
{name = "Insane", rarity = 10},
{name = "Legendary", rarity = 4},
{name = "Godlike", rarity = 1},
}
local function generateXPForItem(itemName)
if itemName == "Common" then
return math.random(5, 10)
elseif itemName == "Uncommon" then
return math.random(15, 25)
elseif itemName == "Rare" then
return math.random(75, 200)
elseif itemName == "Insane" then
return math.random(300, 800)
elseif itemName == "Legendary" then
return math.random(1000, 1200)
elseif itemName == "Godlike" then
return math.random(1500, 2500)
else
return 0 -- default XP if no match found
end
end
local function selectRandomItem()
local totalRarity = 0
for _, item in ipairs(BoxOne) do
totalRarity = totalRarity + item.rarity
end
local randomValue = math.random() * totalRarity
local cumulativeRarity = 0
for _, item in ipairs(BoxOne) do
cumulativeRarity = cumulativeRarity + item.rarity
if randomValue <= cumulativeRarity then
-- Now generate the xp at the time of selection
item.xp = generateXPForItem(item.name)
return item
end
end
end