83 lines
2.6 KiB
Lua
83 lines
2.6 KiB
Lua
local HASH_SEPARATOR = ','
|
|
|
|
local extend = Class.extend
|
|
|
|
local tableInsert, tableCopy, tableSort, tableConcat, tableIsEmpty = table.insert, table.copy, table.sort, table.concat, table.is_empty
|
|
|
|
local modInfo = Mod.getInfo('smc__core__craft_system')
|
|
local require = modInfo.require
|
|
|
|
---@type CraftSystem.BaseCraftHandler
|
|
local BaseCraftHandler = require('CraftSystem.BaseCraftHandler')
|
|
|
|
---@type CraftSystem.ProcessingCraft
|
|
local ProcessingCraft = require('CraftSystem.ProcessingCraft')
|
|
|
|
---A primitive crafting processor that doesn't require much interaction and provides
|
|
---simple crafting based on a recipe-result scheme.
|
|
---@class CraftSystem.ProcessingCraftHandler : CraftSystem.BaseCraftHandler
|
|
---@field craftsByHash table<string, CraftSystem.ProcessingCraft>
|
|
---@field getCraftByName fun(self, craftName:string):CraftSystem.ProcessingCraft
|
|
---@field getCraftsByGroup fun(self, craftGroup:string):CraftSystem.ProcessingCraft[]
|
|
---@field getLearnedCrafts fun(self, playerName:string):(CraftSystem.ProcessingCraft[]|CraftSystem.ProcessingCraft)[]
|
|
local ProcessingCraftHandler = extend(BaseCraftHandler, {
|
|
craftsByHash = {}
|
|
})
|
|
|
|
---@param recipe CraftSystem.CraftRecipe
|
|
local function getCraftHash(recipe)
|
|
recipe = tableCopy(recipe)
|
|
|
|
tableSort(recipe)
|
|
return tableConcat(recipe, HASH_SEPARATOR)
|
|
end
|
|
|
|
---Register a primitive craft that does not require special interaction.
|
|
---@param craftName string
|
|
---@param def CraftSystem.ProcessingCraftDef
|
|
function ProcessingCraftHandler:registerCraft(craftName, def)
|
|
assert(self.craftsByName[craftName] == nil, ('A craft named `%s` already exists.'):format(
|
|
craftName))
|
|
|
|
local group = 'craft_group:' .. (def.group or 'UNDEFINED')
|
|
def.group = group
|
|
|
|
local craft = ProcessingCraft:new(craftName, def)
|
|
|
|
if self.craftsByGroup[group] == nil then
|
|
self.craftsByGroup[group] = {}
|
|
end
|
|
|
|
local craftHash = getCraftHash(craft.recipe)
|
|
assert(self.craftsByHash[craftHash] == nil, 'A craft with this recipe already exists.')
|
|
|
|
self.craftsByName[craftName] = craft
|
|
tableInsert(self.craftsByGroup[group], craft)
|
|
tableInsert(self.craftsList, craft)
|
|
self.craftsByHash[craftHash] = craft
|
|
end
|
|
|
|
---@param input ItemStack[]
|
|
---@return CraftSystem.ProcessingCraft?
|
|
function ProcessingCraftHandler:getCraftByRecipe(input)
|
|
local recipe = {}
|
|
for _, item in ipairs(input) do
|
|
if not item:is_empty() then
|
|
tableInsert(recipe, item:get_name())
|
|
end
|
|
end
|
|
|
|
if tableIsEmpty(recipe) then
|
|
return nil
|
|
end
|
|
|
|
-- TODO: добавить поиск по группам крафтов
|
|
|
|
local craftHash = getCraftHash(recipe)
|
|
local craft = self.craftsByHash[craftHash]
|
|
|
|
return craft
|
|
end
|
|
|
|
return ProcessingCraftHandler
|