Hello there, I know you have probably seen all of the rng games popping up all over roblox and you might be asking yourself how the interworkings are made. Well here is some basic code that you can use to randomly get a item from a database based off of rarity!
local items = {
{
["Name"] = "Common",
["Id"] = "common",
["Rarity"] = 1
},
{
["Name"] = "Uncommon",
["Id"] = "uncommon",
["Rarity"] = 5
},
{
["Name"] = "Rare",
["Id"] = "rare",
["Rarity"] = 30
},
{
["Name"] = "Epic",
["Id"] = "epic",
["Rarity"] = 80
},
{
["Name"] = "Legendary",
["Id"] = "epic",
["Rarity"] = 300
},
{
["Name"] = "God",
["Id"] = "god",
["Rarity"] = 100000
}
}
local function getRandomItem()
local possibleItems = {}
for _, item in next, items do
local number = math.random(1, item.Rarity)
if number ~= 1 then continue end
table.insert(possibleItems, item)
end
local bestItem = nil
for _, possibleItem in next, possibleItems do
if bestItem == nil then bestItem = possibleItem continue end
if possibleItem.Rarity < bestItem.Rarity then continue end
if possibleItem.Rarity == bestItem.Rarity then
local switch = math.random(1, 2) == 1
if not switch then continue end
end
bestItem = possibleItem
end
return bestItem
end
-- DELETE THIS
while true do
local item = getRandomItem()
print(item.Name, item.Id, string.format("1 / %d", item.Rarity))
task.wait()
end
How dose it work:
Well it loops through all of the items in the items table and generates a random number from 1 to rarity. Then if the number is 1 it adds it to a list of possible items. Then It gets the best item from the list and returns it. Also if 2 items are the same rarity it just picks a random one.
How to use this code:
All you need to do is add your own custom items to the list.
You should probably put them inside a module script and then require that.
And then when you want to get a random item just call the getRandomItem() function!
Thanks for reading and if you want to see this system in action I made a video using something similar to this here.