64 lines
2.6 KiB
Text
64 lines
2.6 KiB
Text
# crafting.ludic — RPG Module C: a data-driven crafting registry (#59).
|
|
#
|
|
# Recipes are content, not code: register with Craft.recipe + Craft.ingredient, so a
|
|
# game or mod adds crafting with zero code. Craft.make consumes ingredients from the
|
|
# ludic.rpg Inventory and yields the output; every step is a veto-able event.
|
|
|
|
import "ludic.rpg/inventory.ludic"
|
|
|
|
const CRAFT_MAX: int = 128
|
|
const CRAFT_ING_MAX: int = 512
|
|
|
|
|
|
|
|
event cancellable CraftRequested { e: int = 0, recipe: int = 0 }
|
|
event CraftCompleted { e: int = 0, recipe: int = 0 }
|
|
|
|
# Craft.recipe(name, out_item, out_qty) — declare a recipe; returns its id.
|
|
@Namespace(Craft) function craft_recipe(rpg_st: mut RpgState, name: pointer, out_item: pointer, out_qty: int) -> int {
|
|
if rpg_st.recipe_n >= CRAFT_MAX { return -1 }
|
|
let id = rpg_st.recipe_n
|
|
rpg_st.recipe_out[id] = out_item; rpg_st.recipe_outqty[id] = out_qty
|
|
rpg_st.recipe_n += 1
|
|
Dict.set(rpg_st.recipe_reg, name, id)
|
|
return id
|
|
}
|
|
@Namespace(Craft) function craft_id(rpg_st: mut RpgState, name: pointer) -> int { return Dict.get_or(rpg_st.recipe_reg, name, -1) }
|
|
# Craft.ingredient(recipe_name, item, qty) — add an ingredient requirement.
|
|
@Namespace(Craft) function craft_ingredient(rpg_st: mut RpgState, recipe_name: pointer, item: pointer, qty: int) -> void {
|
|
let rid = craft_id(rpg_st, recipe_name)
|
|
if rid < 0 { return }
|
|
if rpg_st.ing_n >= CRAFT_ING_MAX { return }
|
|
rpg_st.ing_rid[rpg_st.ing_n] = rid; rpg_st.ing_name[rpg_st.ing_n] = item; rpg_st.ing_qty[rpg_st.ing_n] = qty
|
|
rpg_st.ing_n += 1
|
|
}
|
|
|
|
# Craft.can(e, recipe_name) — does the owner hold every ingredient?
|
|
@Namespace(Craft) function craft_can(rpg_st: mut RpgState, e: int, recipe_name: pointer) -> int {
|
|
let rid = craft_id(rpg_st, recipe_name)
|
|
if rid < 0 { return 0 }
|
|
var i = 0
|
|
while i < rpg_st.ing_n {
|
|
if rpg_st.ing_rid[i] == rid {
|
|
if Inventory.count(e, rpg_st.ing_name[i]) < rpg_st.ing_qty[i] { return 0 }
|
|
}
|
|
i += 1
|
|
}
|
|
return 1
|
|
}
|
|
|
|
# Craft.make(e, recipe_name) — consume ingredients + produce output; 1 on success.
|
|
@Namespace(Craft) function craft_make(rpg_st: mut RpgState, e: int, recipe_name: pointer) -> int {
|
|
let rid = craft_id(rpg_st, recipe_name)
|
|
if rid < 0 { return 0 }
|
|
if craft_can(rpg_st, e, recipe_name) == 0 { return 0 }
|
|
if emit CraftRequested(e: e, recipe: rid) != 0 { return 0 }
|
|
var i = 0
|
|
while i < rpg_st.ing_n {
|
|
if rpg_st.ing_rid[i] == rid { Inventory.remove(e, rpg_st.ing_name[i], rpg_st.ing_qty[i]) }
|
|
i += 1
|
|
}
|
|
Inventory.add(e, rpg_st.recipe_out[rid], rpg_st.recipe_outqty[rid])
|
|
emit CraftCompleted(e: e, recipe: rid)
|
|
return 1
|
|
}
|