Weighted Choice
by rehhouari

Weighted Choice
This Godot 4 plugin provides a static WeightedChoice.pick()
method you can call to randomly choose an item from a dictionary based on weights.
Usage:
Includes in-editor documentation!
pick(dict: Dictionary, weight_key: Variant)
Takes a dictionary dict
, and randomly picks one item based based on weights.
If weight_key
is set, the function will search for weights in a nested dictionary.
Returns a key.
Examples
# Define weights for ease of use & consistency
const Rarity = {
"COMMON":0.85,
"UNCOMMON": 0.10,
"RARE": 0.05
}
Non-nested weights:
var dict = {
"A": Rarity.COMMON,
"B": Rarity.UNCOMMON,
"C": Rarity.RARE
}
var key = WeightedChoice.pick(dict) # "A", "B", or "C"
Nested weights
var dict = {
"copper": {"name": "Copper item", "rarity": Rarity.COMMON},
"silver": {"name": "Silver item", "rarity": Rarity.UNCOMMON},
"gold": {"name": "Gold item", "rarity": Rarity.RARE}
}
var key = WeightedChoice.pick(dict, "rarity") # "copper", "silver", or "gold"
Loot Box Demo
You can check the loot box demo for an example on how to use this plugin
Installation
Install from the Asset Library, or clone the repository and copy the weighted_choice folder into your addons folder.
When installing, you can uncheck the "demo" folder
Credits
MIT License
Copyright (c) 2023 Rafik El Hadi Houari
Uses code from Mickeon
godotengine/godot-proposals#3948 (comment)
mentioend in: https://youtu.be/lckgjXM3CeE
Demo assets:
https://admurin.itch.io/free-chest-animations
https://snowhex.itch.io/mini-tools-pack-harvestsummer
Download
Support
If you need help or have questions about this plugin, please contact the author.
Contact Author