This Godot 4 plugin provides a static WeightedChoice.pick()
method you can call to randomly choose an item from a dictionary based on weights.
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.
# Define weights for ease of use & consistency
const Rarity = {
"COMMON":0.85,
"UNCOMMON": 0.10,
"RARE": 0.05
}
var dict = {
"A": Rarity.COMMON,
"B": Rarity.UNCOMMON,
"C": Rarity.RARE
}
var key = WeightedChoice.pick(dict) # "A", "B", or "C"
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"
You can check the loot box demo for an example on how to use this plugin
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
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