Hello! I’m doing my first game with pets and I need that random system. How should I do it?

an example:

*dog 80%

*cat 19.5%

*bird 0.5%

This is how I pick a random num, it prints 10.51, 43.35, 0.87 etc

`num = (math.random(0,10000)) / 100`

Hello! I’m doing my first game with pets and I need that random system. How should I do it?

an example:

*dog 80%

*cat 19.5%

*bird 0.5%

This is how I pick a random num, it prints 10.51, 43.35, 0.87 etc

`num = (math.random(0,10000)) / 100`

You wouldn’t need to divide it. Lua is not like Javascript.

1 Like

math.random returns an integer, he doesn’t want an integer. Of course, he could just make his percentages integers.

1 Like

```
Random.new():NextNumber(0.01, 100)
```

5 Likes

```
local Chances = {
{"dog", .8},
{"cat", .195},
{"bird"} -- bird will be the remaining percentage, so 1 - (.8+.195) = .005. Always have exactly one value with no number
}
local function GetChance()
local percent = math.random()
local current = 0
local default
for i, v in ipairs(Chances) do
if v[2] then
if (v[2]+current) >= percent then
return v[1]
else
current += v[2]
end
else
default = v[1]
end
end
return default
end
```

1 Like

Correct me if I am wrong, you want a system that picks one of those values based on a percentage you get from the provided code.

Here is the code I wrote for this:

```
local pets = {
["Dog"] = 25.5,
["Cat"] = 24.5,
["Bird"] = 50
}
local function pickAPet()
--Picks a number
local num = (math.random(0,10000)) / 100
--Variable Used in Loop
local sum = 0
--Loop runs though the pets and their percents
for pet, percent in pairs(pets) do
--Adds the current pet's percent to the sum
sum = sum + percent
--If the num is less than the sum the num was in the range of the percent
if num < sum then
--returns the pet(in string(word) form). Ex. math.random returns a number.
return pet
end
end
--If your percents add to less than 100 there is a chance no pet will be found. Can be set to a default pet just in case(ex. "Dog")
return "nopet"
end
--Checks if this works(it does)
local times = 1000--must be an int
local bird = 0
local cat = 0
local dog = 0
for i = 1,times do
local pet = pickAPet()
if pet == "Bird" then
bird = bird + 1
end
if pet == "Cat" then
cat = cat + 1
end
if pet == "Dog" then
dog = dog + 1
end
end
print("Cat")
print(cat/(times/100))
print("Dog")
print(dog/(times/100))
print("Bird")
print(bird/(times/100))
```

The bottom is a check to see if it works(It’s a test I used and I thought it would be nice to have).

2 Likes