project-dung/scripts/RecipeDB.gd
2022-08-15 23:47:01 -04:00

55 lines
1.2 KiB
GDScript

extends Resource
class_name RecipeDB
export(Array, Resource) var recipes
func validate():
for recipe in recipes:
if recipe == null:
assert(0)
return false
for item_type in recipe.item_type_slots:
if item_type == null:
assert(0)
return false
return true
func find_recipe(in_item_types) -> Resource:
assert(in_item_types.size() != 0)
var in_items = {}
for in_item_type in in_item_types:
if in_items.has(in_item_type):
in_items[in_item_type] += 1
else:
in_items[in_item_type] = 1
for recipe in recipes:
assert(recipe != null)
if recipe.item_type_out == null or recipe.item_type_slots.size() == 0:
continue
var items = recipe.item_type_slots
# build cost map
var total_cost = {}
for item_type in items:
assert(item_type != null)
if item_type == null:
continue
if total_cost.has(item_type):
total_cost[item_type] += 1
else:
total_cost[item_type] = 1
# check if you can afford the cost
var cost_met : bool = true
for item_type in total_cost.keys():
if not in_items.has(item_type):
cost_met = false
break
if in_items[item_type] < total_cost[item_type]:
cost_met = false
break
if cost_met:
return recipe.item_type_out
return null