Skip to content

rehhouari/WeightedChoice

Repository files navigation

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

screenshot of the loot box demo

You can check the loot box demo for an example on how to use this plugin

Try it in the browser

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