Модуль:Песочница/Pok: различия между версиями

мНет описания правки
мНет описания правки
Строка 4: Строка 4:
-- Загрузка данных  
-- Загрузка данных  
---------------------------------------------------------------------
---------------------------------------------------------------------
local itemData           = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local itemData             = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local tableData         = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data")
local tableData           = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data")
local gearData           = mw.loadData("Модуль:IanComradeBot/startingGear.json/data")
local gearData             = mw.loadData("Модуль:IanComradeBot/startingGear.json/data")
local jobData           = mw.loadData("Модуль:IanComradeBot/job.json/data")
local jobData             = mw.loadData("Модуль:IanComradeBot/job.json/data")
local gearRoleLoadout   = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
local gearRoleLoadout     = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
local loadoutData       = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
local loadoutData         = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
local loadoutGroupData   = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
local loadoutGroupData     = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
local cargoData         = mw.loadData("Модуль:IanComradeBot/prototypes/сargo.json/base")
local cargoData           = mw.loadData("Модуль:IanComradeBot/prototypes/сargo.json/base")
local latheData         = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
local latheData           = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
local recipeData         = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local recipeData           = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local researchData       = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
local researchData         = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
local materialData       = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
local materialData         = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
local chemDataLathe     = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local chemDataLathe       = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local vendingMachinesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines.json/data")
local vendingMachinesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines.json/data")
local inventoriesData     = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/inventories.json/data")
local inventoriesData     = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/inventories.json/data")


---------------------------------------------------------------------
---------------------------------------------------------------------
-- Функции для обратного поиска
-- Вспомогательные функции
---------------------------------------------------------------------
---------------------------------------------------------------------


local function searchItemInStructure(struct, targetId)
-- Обобщённый рекурсивный поиск по полю key с условием predicate
local function searchInStructure(struct, key, predicate)
     if type(struct) ~= "table" then
     if type(struct) ~= "table" then
         return false
         return false
     end
     end
     if struct.id and struct.id == targetId then
     if struct[key] and predicate(struct[key]) then
         return true
         return true
     end
     end
     for _, v in pairs(struct) do
     for _, v in pairs(struct) do
         if type(v) == "table" then
         if type(v) == "table" and searchInStructure(v, key, predicate) then
            if searchItemInStructure(v, targetId) then
            return true
                return true
            end
         end
         end
     end
     end
Строка 41: Строка 40:
end
end


local function searchItemInStructure(struct, targetId)
    return searchInStructure(struct, "id", function(val) return val == targetId end)
end
local function searchTableIdInStructure(struct, tableIds)
    return searchInStructure(struct, "tableId", function(val)
        for _, tid in ipairs(tableIds) do
            if val == tid then return true end
        end
        return false
    end)
end
-- Формирование ссылки для сущности (используется в reverseContained, reverseLathe, reverseVending)
local function createEntityLink(entityId)
    local nameCode = "{{#invoke:Entity Lookup|getname|" .. entityId .. "}}"
    return "[[" .. nameCode .. "|" .. nameCode .. "]]"
end
-- Формирование ссылки для таблицы грузов (reverseCargo)
local function createCargoLink(storage)
    local nameCode = "{{#invoke:Entity Lookup|getname|" .. storage .. "}}"
    return "[[Таблица грузов#" .. nameCode .. "|" .. nameCode .. "]]"
end
-- Формирование ссылки для роли/джоба (reverseEquipment)
local function createJobLink(jobId)
    local translation = "{{#invoke:Ftl|main|translation|" .. jobId .. "}}"
    return "[[" .. translation .. "|{{ucfirst:" .. translation .. "}}]]"
end
---------------------------------------------------------------------
-- Логика поиска
---------------------------------------------------------------------
---------------------------------------------------------------------


local function findRelatedTables(initialList)
local function findRelatedTables(initialList)
     local results = {}  
     local results = {}
     local function recursiveSearch(tblId)
     local function recursiveSearch(tblId)
         if results[tblId] then  
         if results[tblId] then  
Строка 53: Строка 85:
             if type(entry) == "table" then
             if type(entry) == "table" then
                 for _, value in pairs(entry) do
                 for _, value in pairs(entry) do
                     if type(value) == "table" and value.tableId and value.tableId == tblId then
                     if type(value) == "table" and value.tableId == tblId then
                         recursiveSearch(id)
                         recursiveSearch(id)
                     end
                     end
Строка 70: Строка 102:
end
end


local function searchTableIdInStructure(struct, tableIds)
    if type(struct) ~= "table" then
        return false
    end
    if struct.tableId then
        for _, tid in ipairs(tableIds) do
            if struct.tableId == tid then
                return true
            end
        end
    end
    for _, v in pairs(struct) do
        if type(v) == "table" then
            if searchTableIdInStructure(v, tableIds) then
                return true
            end
        end
    end
    return false
end
---------------------------------------------------------------------
-- Общая логика поиска хранилищ, содержащих указанный targetId
---------------------------------------------------------------------
local function findMatchingStorages(targetId)
local function findMatchingStorages(targetId)
     local initialTables = {}
     local initialTables = {}
     for key, tblEntry in pairs(tableData) do
     for key, tblEntry in pairs(tableData) do
         if type(tblEntry) == "table" then
         if type(tblEntry) == "table" and searchItemInStructure(tblEntry, targetId) then
            if searchItemInStructure(tblEntry, targetId) then
            local tableId = tblEntry.id or key
                local tableId = tblEntry.id or key
            table.insert(initialTables, tableId)
                table.insert(initialTables, tableId)
            end
         end
         end
     end
     end


     local allRelatedTables = {}
     local allRelatedTables = (#initialTables > 0) and findRelatedTables(initialTables) or {}
    if #initialTables > 0 then
        allRelatedTables = findRelatedTables(initialTables)
    end


     local matchingStorages = {}
     local matchingStorages = {}
Строка 114: Строка 117:
         if type(storage) == "table" then
         if type(storage) == "table" then
             local found = false
             local found = false
             if storage.EntityTableContainerFill  
             if storage.EntityTableContainerFill  
               and storage.EntityTableContainerFill.containers then
               and storage.EntityTableContainerFill.containers then
Строка 121: Строка 123:
                 end
                 end
             end
             end
             if searchItemInStructure(storage, targetId) then
             if searchItemInStructure(storage, targetId) then
                 found = true
                 found = true
             end
             end
             if found then
             if found then
                 local actualId = storage.id or storageKey
                 local actualId = storage.id or storageKey
Строка 137: Строка 137:


---------------------------------------------------------------------
---------------------------------------------------------------------
-- Функции обратного поиска
---------------------------------------------------------------------
function p.reverseContained(frame)
function p.reverseContained(frame)
     local targetId = frame.args[2]
     local targetId = frame.args[2]
Строка 162: Строка 165:
     end
     end


local filteredStoragesLinks = {}
    local links = {}
for _, storage in ipairs(filteredStorages) do
    for _, storage in ipairs(filteredStorages) do
    table.insert(filteredStoragesLinks, "[[{{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
        table.insert(links, createEntityLink(storage))
end
    end


     return "Находится в хранилище: " .. table.concat(filteredStoragesLinks, ", ")
     return "Находится в хранилище: " .. table.concat(links, ", ")
end
end


---------------------------------------------------------------------
function p.reverseEquipment(frame)
function p.reverseEquipment(frame)
     local targetId = frame.args[2]
     local targetId = frame.args[2]
Строка 194: Строка 196:
                     end
                     end
                     if foundJob then
                     if foundJob then
                         table.insert(results, "[[{{#invoke:Ftl|main|translation|" .. foundJob .. "}}|{{ucfirst:{{#invoke:Ftl|main|translation|" .. foundJob .. "}}}}]]")
                         table.insert(results, createJobLink(foundJob))
                     end
                     end
                 end
                 end
Строка 207: Строка 209:
                 if equipId == targetId and (not slotFilter or slot == slotFilter) then
                 if equipId == targetId and (not slotFilter or slot == slotFilter) then
                     local foundGroupId = nil
                     local foundGroupId = nil
                    -- Поиск группы в loadoutGroupData, в которой присутствует loadout.id
                     for _, group in pairs(loadoutGroupData) do
                     for _, group in pairs(loadoutGroupData) do
                         if group.loadouts and type(group.loadouts) == "table" then
                         if group.loadouts and type(group.loadouts) == "table" then
Строка 220: Строка 221:
                     end
                     end
                     local foundJob = nil
                     local foundJob = nil
                    -- Поиск роли в gearRoleLoadout, где группы содержат найденный id группы
                     if foundGroupId then
                     if foundGroupId then
                         for _, role in pairs(gearRoleLoadout) do
                         for _, role in pairs(gearRoleLoadout) do
Строка 235: Строка 235:
                     end
                     end
                     if foundJob then
                     if foundJob then
                         table.insert(results, "[[{{#invoke:Ftl|main|translation|" .. foundJob .. "}}|{{ucfirst:{{#invoke:Ftl|main|translation|" .. foundJob .. "}}}}]]")
                         table.insert(results, createJobLink(foundJob))
                     end
                     end
                 end
                 end
Строка 249: Строка 249:
end
end


---------------------------------------------------------------------
function p.reverseCargo(frame)
function p.reverseCargo(frame)
     local searchValue = frame.args[2]
     local searchValue = frame.args[2]
Строка 256: Строка 255:
     end
     end


     -- Сначала ищем прямые совпадения в cargoData по product
     -- Сначала ищем прямые совпадения по product
     local directCargo = {}
     local directCargo = {}
     for _, entry in ipairs(cargoData) do
     for _, entry in ipairs(cargoData) do
Строка 268: Строка 267:
     end
     end


     -- Если не найдено прямых совпадений, выполняем обратный поиск как в reverseContained,
     -- Если прямых совпадений нет, выполняем обратный поиск среди хранилищ
    -- но оставляем только те хранилища, которые присутствуют в cargoData (т.е. имеют product равный их id)
     local matchingStorages = findMatchingStorages(searchValue)
     local matchingStorages = findMatchingStorages(searchValue)
     local cargoStorages = {}
     local cargoStorages = {}
Строка 284: Строка 282:
         return ""
         return ""
     end
     end
      
 
local cargoLinks = {}
     local links = {}
for _, storage in ipairs(cargoStorages) do
    for _, storage in ipairs(cargoStorages) do
    table.insert(cargoLinks, "[[Таблица грузов#{{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
        table.insert(links, createCargoLink(storage))
end
    end
return "Заказ груза: " .. table.concat(cargoLinks, ", ")
    return "Заказ груза: " .. table.concat(links, ", ")
end
end


---------------------------------------------------------------------
local function getRecipeById(recipeId)
local function getRecipeById(recipeId)
     for _, recipe in ipairs(recipeData) do
     for _, recipe in ipairs(recipeData) do
Строка 340: Строка 337:
     end
     end


local matchingLathesLinks = {}
    local links = {}
for _, storage in ipairs(matchingLathes) do
    for _, latheId in ipairs(matchingLathes) do
    table.insert(matchingLathesLinks, "[[{{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
        table.insert(links, createEntityLink(latheId))
end
    end


     return "Может быть напечатано на станке: " .. table.concat(matchingLathesLinks, ", ")
     return "Может быть напечатано на станке: " .. table.concat(links, ", ")
end
end


---------------------------------------------------------------------
function p.reverseVending(frame)
function p.reverseVending(frame)
     local invMode = frame.args[2] or ""  -- режим поиска: "inventory", "contraband", "emag" или пустая строка для всех
     local invMode = frame.args[2] or ""  -- режим: "inventory", "contraband", "emag" или пустая строка для всех
     local targetId = frame.args[3]
     local targetId = frame.args[3]
     if not targetId or targetId == "" then
     if not targetId or targetId == "" then
         return "Ошибка: не указан id предмета для обратного поиска в торговых автоматах."
         return "Ошибка: не указан id предмета для обратного поиска в торговых автоматах."
     end
     end
    -- Определяем соответствующие ключи для поиска в инвентарях
    local inventoryTypes = {
        inventory  = "startingInventory",
        contraband  = "contrabandInventory",
        emag        = "emaggedInventory"
    }


     local matchingInventoryIds = {}
     local matchingInventoryIds = {}
    -- Перебираем все инвентарные записи
     for _, inventory in pairs(inventoriesData) do
     for _, inventory in pairs(inventoriesData) do
         if inventory.id then
         if inventory.id then
             local found = false
             local found = false
             if (invMode == "inventory" or invMode == "" or not invMode) and inventory.startingInventory and type(inventory.startingInventory) == "table" then
             if invMode ~= "" then
                if inventory.startingInventory[targetId] then
                local key = inventoryTypes[invMode]
                if key and inventory[key] and type(inventory[key]) == "table" and inventory[key][targetId] then
                     found = true
                     found = true
                 end
                 end
             end
             else
            if (invMode == "contraband" or invMode == "" or not invMode) and inventory.contrabandInventory and type(inventory.contrabandInventory) == "table" then
                for _, key in pairs(inventoryTypes) do
                if inventory.contrabandInventory[targetId] then
                    if inventory[key] and type(inventory[key]) == "table" and inventory[key][targetId] then
                    found = true
                        found = true
                end
                        break
            end
                    end
            if (invMode == "emag" or invMode == "" or not invMode) and inventory.emaggedInventory and type(inventory.emaggedInventory) == "table" then
                if inventory.emaggedInventory[targetId] then
                    found = true
                 end
                 end
             end
             end
Строка 389: Строка 389:
     for _, vm in pairs(vendingMachinesData) do
     for _, vm in pairs(vendingMachinesData) do
         if vm.VendingMachine and vm.VendingMachine.pack then
         if vm.VendingMachine and vm.VendingMachine.pack then
            local packId = vm.VendingMachine.pack
             for _, invId in ipairs(matchingInventoryIds) do
             for _, invId in ipairs(matchingInventoryIds) do
                 if packId == invId then
                 if vm.VendingMachine.pack == invId then
                     if vm.id then
                     if vm.id then
                         table.insert(matchingVendingMachines, vm.id)
                         table.insert(matchingVendingMachines, vm.id)
Строка 404: Строка 403:
         return ""
         return ""
     end
     end
   
    local matchingVendingMachinesLinks = {}
for _, storage in ipairs(matchingVendingMachines) do
    table.insert(matchingVendingMachinesLinks, "[[{{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
end


     return "Содержится в торгомате: " .. table.concat(matchingVendingMachinesLinks, ", ")
     local links = {}
    for _, vmId in ipairs(matchingVendingMachines) do
        table.insert(links, createEntityLink(vmId))
    end
 
    -- Разные текстовые сообщения для каждого режима
    local modeTexts = {
        inventory  = "В торговом автомате (инвентарь): ",
        contraband = "В торговом автомате (контрабанда): ",
        emag      = "В торговом автомате (эмаг): "
    }
    local outputText = modeTexts[invMode] or "Содержится в торгомате: "
    return outputText .. table.concat(links, ", ")
end
end