A
A
anubis4652020-08-01 09:00:28
JavaScript
anubis465, 2020-08-01 09:00:28

How to correctly implement the drop chance?

I want to make a game bot, but somehow it doesn't work. I need to make it so that when writing a command, the bot would send a certain message with a chance. Let's say we have 4 items:
1 item with a 30% chance
2 item with a 40% chance
3 item with a 50% chance
4 item with a 60% chance The
bot should send a message according to the chance. I was looking for a question on this topic and found the code:

const items = [
    {
        name: 'Apple',
        dropChance: 0.7
    },
    {
        name: 'Knife',
        dropChance: 0.25
    },
    {
        name: 'Spoon',
        dropChance: 0.25
    },
    {
        name: 'Ice Cream',
        dropChance: 0.1
    }
];

const lerp = (min, max, value) => ((1 - value) * min + value * max);

const drop = items => {
    const total = items.reduce((accumulator, item) => (accumulator += item.dropChance), 0);
    const chance = lerp(0, total, Math.random());

    let current = 0;
    for (const item of items) {
        if (current <= chance && chance < current + item.dropChance) {
            return item;
        }

        current += item.dropChance;
    }
};

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2020-08-01
@anubis465

familiar code . Well, what's the problem then?

K
Karpion, 2020-08-01
@Karpion

Excuse me, but why do you have the amount of interest = 180%? Churov, relogin!
If the percentages are round, then you can do something like this:
We make an array {1,1,1,2,2,2,2,3,3,4}. We make a random integer from 0 to 9 (take float a random number from 0 to 1, multiply by 10, take the integer part rounded down). We use this number as an index in the array, we get the number of the dropped item.
If the percentages are not round, then float a random number from 0 to 1. Then, in turn, subtract from it the percentages of the probability of items falling out until it becomes . If there are a lot of objects, then we write to the array not the probabilities themselves, but the sum of the previous probabilities - and look for the halving method. I'm too lazy to paint - but at a separate request I can sketch an example. <=0

B
bqio, 2020-08-01
@bqio

https://jsfiddle.net/h7yLm1fp/5/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question