Created
March 19, 2023 21:38
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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