I have a pet that chooses a pet, but I don’t want all the pets to have an equal chance. I want it to read from a list of the percentage of the pet (look below). But I don’t want the value to be hardcoded incase I want to change it in the future.
I tried to use math.random() but since the numbers are the same, that didn’t work. Then I tried using a weight system, but that create the same problem as before, they all had a equal chance.
for i = 1,#percent do
if math.Random(percent[i],100) == 1 then
-- They got it give them pet
break
end
end
This way it doesnt have to add up to 100. Though I would add something at the end that is 100% chance just in case they don’t get anything before then.
You change the values next to the pets name(the next element in the table)
In your case to get a random pet youll need to (i recommend looking at the post if you want to understand more because im pretty much copy and pasting code from there)
local Pets = {
{"Pet1",7},
{"Pet2",2},
{"Pet3",10},
{"Pet4",30},
-- you can add as many pets as you want here and just change the value
}
local TotalWeight = 0
for _,ItemData in pairs(Pets) do
TotalWeight = TotalWeight + ItemData[2]
end
local function chooseRandomItem()
local Chance = math.random(1,TotalWeight)
local Counter = 0
for _,ItemData in pairs(Pets) do
Counter = Counter + ItemData[2]
if Chance <= Counter then
return ItemData[1]
end
end
end
local randomPet = chooseRandomItem()
print(randomPet)
If you want some items to have the same rarity just use the same value for them
local Pets = {
{"Pet1",7},
{"Pet2",2},
{"Pet3",10},
{"Pet4",30},
{"Pet5",30}
--[[you can add as many pets as you want here and just change the value
Pet5 and Pet4 would have the same chance in this instance
]]
}
local percent = {
Pet1 = {1, 20};
Pet2 = {21, 40};
Pet3 = {41, 60};
Pet4 = {61, 80};;
Pet5 = {81, 90};
Pet6 = {91, 100};
}
local function RandomPet()
local RandNum = math.random(1, 100)
local ChosenPet
for name, numbers in pairs(percent) do
if RandNum >= numbers[1] and RandNum <= numbers[2] then
ChosenPet = name
end
end
print(ChosenPet .. " was chosen.")
end
Each pet has their own numbers inside the range of 1-100, it’s sort of like a ticket system where some pets have more tickets than others. For example pet 1 has all the tickets between the numbers 1 and 20. The script picks a random number (ticket) between 1 and 100 and sees which pet has that ticket. It then prints which pet was chosen.