Skip to content

Instantly share code, notes, and snippets.

@onderaltintas
Created March 19, 2023 21:38
Show Gist options
  • Save onderaltintas/f95d53031f5871600c46d10c0749ad0b to your computer and use it in GitHub Desktop.
Save onderaltintas/f95d53031f5871600c46d10c0749ad0b to your computer and use it in GitHub Desktop.
Let's say we are making a rpg hack and slash game, there are 5 item drops. Drop chances differs. This function calculates which item will drop based on their probabilities. I didn't write it, chatGPT did.
function rollForDrop() {
// List of items, with their drop chances as weights
const items = {
"Sword": 0.2,
"Shield": 0.1,
"Potion": 0.3,
"Gold": 0.25,
"Gem": 0.15
};
// Calculate total weight of all items
const totalWeight = Object.values(items).reduce((acc, val) => acc + val, 0);
// Roll the die and determine which item dropped
const roll = Math.random() * totalWeight;
let weightSum = 0;
for (const [item, weight] of Object.entries(items)) {
weightSum += weight;
if (roll <= weightSum) {
return item;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment