← Pixel Dreamer Studio

Check crafting recipes in any order, with the right counts

Count each ingredient into a Dictionary and compare it with the recipe's counts.

Turn both the recipe and the player's ingredients into a Dictionary of ingredient to count, and compare the two with ==. In Godot 4 that compares keys and counts and ignores the order. In our Godot 4.7 test, comparing arrays missed a Healing Pill put in as Moon Dew, Spirit Grass, Spirit Grass, and checking that every recipe item was present with has() gave the wrong answer for 4 of the 6 mixes. The script got all 6 right.

The code

Create one, add each recipe once with add_recipe(), then call find_recipe() with whatever the player put in the pot, crafting grid or forge. It returns the recipe's name, or an empty string when the mix makes nothing. Ingredients can be anything that works as a Dictionary key, such as names or item IDs.

extends RefCounted
## Finds the recipe a set of ingredients makes: any order, and the counts must match exactly.

var recipes := {}  # recipe name -> {ingredient: count}


func add_recipe(recipe_name: String, ingredients: Array) -> void:
	recipes[recipe_name] = count(ingredients)


## Returns the recipe name, or "" when the ingredients make nothing.
func find_recipe(ingredients: Array) -> String:
	var have := count(ingredients)
	for r in recipes:
		if recipes[r] == have:  # same keys and counts; the order of the keys does not matter
			return r
	return ""


static func count(items: Array) -> Dictionary:
	var d := {}
	for it in items:
		d[it] = d.get(it, 0) + 1
	return d

What we measured

Two recipes: Healing Pill is 2 Spirit Grass and 1 Moon Dew, Qi Pill is 1 Spirit Grass, 1 Moon Dew and 1 Ember Lotus. Six mixes. Two runs gave the same answers.

Why simple checks go wrong

Two arrays are only equal when every item is in the same place, so the player has to guess the order. has() only asks whether an item is there at all, so it cannot see counts or extra items, and a small recipe matches any bigger mix that contains it. Sorting both lists before comparing does work. It needs a copy first, because sort() changes the array itself: in our test, sorting the player's array without a copy reordered their pot. Counting into a Dictionary skips that.

What to change

A whole pill refining system: Xianxia Alchemy & Pill Refining System for Godot 4 has 9 herbs, 6 recipes, a furnace heat minigame, experimenting to discover recipes, alchemist levels and save and load. Its recipes match herbs and counts in any order the same way.

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