← Pixel Dreamer Studio

Pick from a weighted loot table with the right chances

Give all the weights to RandomNumberGenerator.rand_weighted() and roll once.

Each if randf() < weight in a chain only runs when the ones before it failed, so later entries get a fraction of their chance and sometimes nothing drops at all. In our Godot 4.7 test a 50/30/15/5 table came out 50.0/15.1/5.3/1.4, with nothing 28.1% of the time. Roll once with rng.rand_weighted(weights), available since Godot 4.3.

The code

Make the table a Dictionary of entry and weight, and call pick(table). The weights do not need to add up to 100. It returns null when every weight is 0. Set rng.seed if you need the same rolls every time, for example for a daily reward.

extends Node
## Pick one entry from a weighted table: herb drops, chest rewards, pill quality.
## Weights do not need to add up to 100. Needs Godot 4.3 or newer for rand_weighted().

var rng := RandomNumberGenerator.new()


func pick(table: Dictionary) -> Variant:
	var keys := table.keys()
	var weights := PackedFloat32Array()
	for k in keys:
		weights.append(float(table[k]))
	var i := rng.rand_weighted(weights)  # -1 when every weight is 0
	return keys[i] if i >= 0 else null

What we measured

100,000 rolls of a table with Common Herb 50, Spirit Grass 30, Moon Lotus 15 and Dragon Blood Vine 5, with a fixed seed. Two runs with the same numbers.

Why it happens

A chain rolls a new number for every entry, and an entry is only reached when every roll before it failed. Spirit Grass is only checked when Common Herb missed, half of the time, so it gets 30% of 50%: 15%. Nothing drops when all four miss: 50% × 70% × 85% × 95% is about 28%. rand_weighted() rolls once over the total of all weights, so each entry gets exactly its share. If you want a chance of no drop, put it in the table as its own entry.

What to change

Chances that miss too many times in a row: pseudo-random chance. Recipes that work in any order: crafting recipe check.

A ready-made system: Xianxia Alchemy & Pill Refining System for Godot 4 has herbs, recipes, a furnace heat minigame, experimenting to discover recipes, levels and save/load.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: Xianxia Alchemy & Pill Refining System for Godot 4 has herbs, recipes, a furnace heat minigame, experimenting to discover recipes, levels and save/load.

More how-tos: Game systems