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

Материал из Space Station 14 Вики
мНет описания правки
мНет описания правки
 
(не показано 150 промежуточных версий этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}


---------------------------------------------------------------------
-- Загрузка данных
-- Загрузка данных  
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
---------------------------------------------------------------------
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
-- Данные для модуля, работающего с содержимым/контейнерами
local itemData          = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local tableData        = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data")
local itemSlotsData    = mw.loadData("Модуль:IanComradeBot/prototypes/ItemSlots.json/data")
local itemStackData    = mw.loadData("Модуль:IanComradeBot/prototypes/fills/stack.json/data")
local chemData          = mw.loadData("Модуль:IanComradeBot/prototypes/fills/chem.json/data")
local chemTranslateData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")


-- Данные для модуля экипировки/должностей
local function kelvinToCelsius(k)
local jobData          = mw.loadData("Модуль:IanComradeBot/job.json/data")
    return k - 273.15
local gearData          = mw.loadData("Модуль:IanComradeBot/startingGear.json/data")
end
local gearRoleLoadout  = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
local gearloadout      = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
local gearloadoutGroup  = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")


-- Данные для модуля грузов
local function findSeedById(id, data)
local cargoData         = mw.loadData("Модуль:IanComradeBot/prototypes/сargo.json/base")
    for _, seed in ipairs(data) do
         if seed.id == id then
            return seed
        end
    end
    return nil
end


-- Данные для модуля станков (lathe)
local function formatCharacteristics(seed)
local latheData         = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
    local parts = {
local recipeData        = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
         ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1),
local researchData      = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
        ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield),
local materialData      = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
        ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan),
local latheChemData     = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
        ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation),
        ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production),
        ("[[Гидропоника#Стадии роста|Стадии роста]]: %s"):format(seed.growthStages or 6),
    }
     return table.concat(parts, '<br>')
end


local function reverseFindStorageByItem(itemId, visited)
local function formatConditions(seed)
     visited = visited or {}
     local parts = {
    if visited[itemId] then return "" end
        ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5),
    visited[itemId] = true
        ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75),
        ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)),
    }
    return table.concat(parts, '<br>')
end


     local result = {}
local function formatHarvestType(seed)
    return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
end
local function formatHarvestType(seed)
     local harvestRepeat = seed.harvestRepeat
    if harvestRepeat == "Repeat" then
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
    elseif harvestRepeat == "SelfHarvest" then
        return "[[Гидропоника#Тип урожая|Самосбор]]"
    else
        return "[[Гидропоника#Тип урожая|Однолетнее]]"
    end
end


    local function searchInEntry(entry)
local function formatChemicals(seed)
        if type(entry) == "table" then
    if not seed.chemicals then return "-" end
            if entry.id == itemId then
    local list = {}
                return true
    for chemId, vals in pairs(seed.chemicals) do
            end
        local entry = chemData[chemId]
            for _, v in pairs(entry) do
        local chemName = entry and entry.name or chemId
                if type(v) == "table" then
        table.insert(list, string.format(
                    if searchInEntry(v) then
            "<li>[[Химия#chem_%s|%s]] (мин: %s, макс: %s, дел: %s)</li>",
                        return true
             chemId, chemName, vals.Min or 0, vals.Max or 0, vals.PotencyDivisor or 1
                    end
         ))
                end
             end
         end
        return false
     end
     end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


     for tblId, tblEntry in pairs(tableData) do
local function formatMutations(seed, data)
         if searchInEntry(tblEntry) then
    if not seed.mutationPrototypes then return "-" end
             for storageId, storage in pairs(itemData) do
    local list = {}
                 if storage.StorageFill and storage.StorageFill.tableId == tblId then
     for _, mu in ipairs(seed.mutationPrototypes) do
                    table.insert(result, storageId)
         local target = findSeedById(mu, data)
                elseif storage.EntityTableContainerFill and storage.EntityTableContainerFill.containers then
        if target and target.productPrototypes then
                    local cont = storage.EntityTableContainerFill.containers
             for _, prod in ipairs(target.productPrototypes) do
                    if (cont.entity_storage and cont.entity_storage.tableId == tblId) or
                 table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod))
                      (cont.storagebase and cont.storagebase.tableId == tblId) then
                        table.insert(result, storageId)
                    end
                end
             end
             end
         end
         end
     end
     end
    return "<ul>" .. table.concat(list) .. "</ul>"
end
local function generateHeader()
    return [[
{| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;"
! rowspan="2" style="width:10%;" | Плод
! rowspan="2" class="unsortable" style="width:5%;" | Семена
! rowspan="2" class="unsortable" style="width:5%;" | Растение
! colspan="3" class="unsortable" style="width:30%;" id="no-highlight" | Характеристики
! rowspan="2" class="unsortable" style="width:30%;" | Содержит вещества
! rowspan="2" style="width:20%;" | Мутации
|-
! style="width:10%;" class="unsortable" | Рост
! style="width:10%;" class="unsortable" | Условия
! style="width:5%;" class="unsortable" | Тип сбора
]]
end


     return #result > 0 and table.concat(result, ", ") or ""
local function generateFooter()
     return "|}"
end
end


local function reverseFindJobByItem(itemId)
function p.table(frame)
     local result = {}
    local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
     local rows = {}


     for gearId, gear in pairs(gearData) do
     for _, seed in ipairs(data) do
         if gear.equipment then
         local prodId = seed.productPrototypes[1]
            for slot, equipId in pairs(gear.equipment) do
        local seedId = seed.packetPrototype
                if equipId == itemId then
        local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)
                    table.insert(result, gearId)
                end
            end
        end
    end


    for roleId, role in pairs(gearRoleLoadout) do
        local anchor  = string.format('{{anchor|%s}}', seedName)
         if role.groups then
         local fruitImg = string.format(
             for _, groupId in ipairs(role.groups) do
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}',
                local groupData = gearloadoutGroup[groupId]
             prodId, seedName
                if groupData and groupData.loadouts then
        )
                    for _, loadoutId in ipairs(groupData.loadouts) do
        local seedImg  = string.format(
                        local loadout = gearloadout[loadoutId]
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}',
                        if loadout and loadout.equipment then
            seedId, seedName
                            for slot, equipId in pairs(loadout.equipment) do
        )
                                if equipId == itemId then
        local plantImg = string.format(
                                    table.insert(result, roleId)
            '{{Предмет|%s-harvest|size=64px|l=|link=%s}}',
                                end
             seedId, seedName
                            end
         )
                        end
                    end
                end
             end
         end
    end


     return #result > 0 and table.concat(result, ", ") or ""
        local colGrowth     = formatCharacteristics(seed)
end
        local colConditions = formatConditions(seed)
        local colHarvest    = formatHarvestType(seed)
        local colChemicals  = formatChemicals(seed)
        local colMutations  = formatMutations(seed, data)


local function reverseCargoLookup(field, value)
        local row = frame:preprocess(string.format(
    for _, entry in ipairs(cargoData) do
            [[|-
         if entry[field] and tostring(entry[field]) == tostring(value) then
            ! %s
            return entry.id
            ! %s
        end
            ! %s
            | %s
            | %s
            | %s
            | %s
            | %s ]],
            fruitImg, seedImg, plantImg,
            colGrowth, colConditions, colHarvest,
            colChemicals, colMutations
         ))
        table.insert(rows, row)
     end
     end
    return nil
end


local function reverseFindLatheByProduct(product)
     return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter()
     for _, lathe in ipairs(latheData) do
        local found = false
        if lathe.Lathe then
            if lathe.Lathe.staticRecipes then
                for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
                    for _, recipe in ipairs(recipeData) do
                        if recipe.id == recipeId and recipe.result == product then
                            return lathe.id
                        end
                    end
                end
            end
            if lathe.Lathe.dynamicRecipes then
                for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
                    for _, recipe in ipairs(recipeData) do
                        if recipe.id == recipeId and recipe.result == product then
                            return lathe.id
                        end
                    end
                end
            end
        end
        if lathe.EmagLatheRecipes then
            if lathe.EmagLatheRecipes.emagStaticRecipes then
                for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
                    for _, recipe in ipairs(recipeData) do
                        if recipe.id == recipeId and recipe.result == product then
                            return lathe.id
                        end
                    end
                end
            end
            if lathe.EmagLatheRecipes.emagDynamicRecipes then
                for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
                    for _, recipe in ipairs(recipeData) do
                        if recipe.id == recipeId and recipe.result == product then
                            return lathe.id
                        end
                    end
                end
            end
        end
    end
    return nil
end
end


function p.main(frame)
function p.main(frame)
     local mode = mw.text.trim(frame.args[1] or "")
     local args = frame.args
     local param = mw.text.trim(frame.args[2] or "")
    local id = args[1]
      
     local mode  = mw.text.trim(args[2] or ""):lower()
     if mode == "" or param == "" then
     local seed = findSeedById(id, seedsData)
        return "Ошибка: не указаны необходимые параметры для обратного поиска."
     if not seed then return "" end
    end


     if mode == "reverseStorage" then
     if mode == "growth" then
         local storageResult = reverseFindStorageByItem(param)
         return formatCharacteristics(seed)
        if storageResult ~= "" then
    elseif mode  == "conditions" then
            return "Найденные хранилища (itemData), ссылающиеся на таблицу, содержащую предмет " .. param .. ": " .. storageResult
        return formatConditions(seed)
        else
     elseif mode == "harvest" then
            return "Хранилище не найдено для предмета " .. param
         return formatHarvestType(seed)
        end
     elseif mode == "chemicals" then
     elseif mode == "reverseJob" then
         return formatChemicals(seed)
         local jobResult = reverseFindJobByItem(param)
     elseif mode == "mutations" then
        if jobResult ~= "" then
         return formatMutations(seed, seedsData)
            return "Найденные роли/экипировки, использующие предмет " .. param .. ": " .. jobResult
        else
            return "Нет данных для предмета " .. param
        end
     elseif mode == "reverseCargo" then
         -- Здесь предполагается, что param – значение поля product.
        local cargoId = reverseCargoLookup("product", param)
        if cargoId then
            return "Найден груз с ID: " .. cargoId
        else
            return "Груз не найден по значению " .. param
        end
     elseif mode == "reverseLathe" then
         local latheId = reverseFindLatheByProduct(param)
        if latheId then
            return "Найден станок (lathe) с ID: " .. latheId
        else
            return "Станок не найден для продукта " .. param
        end
     else
     else
         return "Ошибка: неизвестный режим обратного поиска: " .. mode
         return ""
     end
     end
end
end


return p
return p

Текущая версия от 23:43, 26 ноября 2025

Для документации этого модуля может быть создана страница Модуль:Песочница/Pok/doc

local p = {}

-- Загрузка данных
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")

local function kelvinToCelsius(k)
    return k - 273.15
end

local function findSeedById(id, data)
    for _, seed in ipairs(data) do
        if seed.id == id then
            return seed
        end
    end
    return nil
end

local function formatCharacteristics(seed)
    local parts = {
        ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1),
        ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield),
        ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan),
        ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation),
        ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production),
        ("[[Гидропоника#Стадии роста|Стадии роста]]: %s"):format(seed.growthStages or 6),
    }
    return table.concat(parts, '<br>')
end

local function formatConditions(seed)
    local parts = {
        ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5),
        ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75),
        ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)),
    }
    return table.concat(parts, '<br>')
end

local function formatHarvestType(seed)
    return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
end
local function formatHarvestType(seed)
    local harvestRepeat = seed.harvestRepeat
    if harvestRepeat == "Repeat" then
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
    elseif harvestRepeat == "SelfHarvest" then
        return "[[Гидропоника#Тип урожая|Самосбор]]"
    else
        return "[[Гидропоника#Тип урожая|Однолетнее]]"
    end
end

local function formatChemicals(seed)
    if not seed.chemicals then return "-" end
    local list = {}
    for chemId, vals in pairs(seed.chemicals) do
        local entry = chemData[chemId]
        local chemName = entry and entry.name or chemId
        table.insert(list, string.format(
            "<li>[[Химия#chem_%s|%s]] (мин: %s, макс: %s, дел: %s)</li>",
            chemId, chemName, vals.Min or 0, vals.Max or 0, vals.PotencyDivisor or 1
        ))
    end
    return "<ul>" .. table.concat(list) .. "</ul>"
end

local function formatMutations(seed, data)
    if not seed.mutationPrototypes then return "-" end
    local list = {}
    for _, mu in ipairs(seed.mutationPrototypes) do
        local target = findSeedById(mu, data)
        if target and target.productPrototypes then
            for _, prod in ipairs(target.productPrototypes) do
                table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod))
            end
        end
    end
    return "<ul>" .. table.concat(list) .. "</ul>"
end

local function generateHeader()
    return [[
{| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;"
! rowspan="2" style="width:10%;" | Плод
! rowspan="2" class="unsortable" style="width:5%;" | Семена
! rowspan="2" class="unsortable" style="width:5%;" | Растение
! colspan="3" class="unsortable" style="width:30%;" id="no-highlight" | Характеристики
! rowspan="2" class="unsortable" style="width:30%;" | Содержит вещества
! rowspan="2" style="width:20%;" | Мутации
|- 
! style="width:10%;" class="unsortable" | Рост
! style="width:10%;" class="unsortable" | Условия
! style="width:5%;" class="unsortable" | Тип сбора
]]
end

local function generateFooter()
    return "|}"
end

function p.table(frame)
    local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
    local rows = {}

    for _, seed in ipairs(data) do
        local prodId = seed.productPrototypes[1]
        local seedId = seed.packetPrototype
        local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)

        local anchor   = string.format('{{anchor|%s}}', seedName)
        local fruitImg = string.format(
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}',
            prodId, seedName
        )
        local seedImg  = string.format(
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}',
            seedId, seedName
        )
        local plantImg = string.format(
            '{{Предмет|%s-harvest|size=64px|l=|link=%s}}',
            seedId, seedName
        )

        local colGrowth     = formatCharacteristics(seed)
        local colConditions = formatConditions(seed)
        local colHarvest    = formatHarvestType(seed)
        local colChemicals  = formatChemicals(seed)
        local colMutations  = formatMutations(seed, data)

        local row = frame:preprocess(string.format(
            [[|-
            ! %s 
            ! %s 
            ! %s 
            | %s 
            | %s 
            | %s 
            | %s 
            | %s ]],
            fruitImg, seedImg, plantImg,
            colGrowth, colConditions, colHarvest,
            colChemicals, colMutations
        ))
        table.insert(rows, row)
    end

    return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter()
end

function p.main(frame)
    local args = frame.args
    local id = args[1]
    local mode  = mw.text.trim(args[2] or ""):lower()
    local seed = findSeedById(id, seedsData)
    if not seed then return "" end

    if mode  == "growth" then
        return formatCharacteristics(seed)
    elseif mode  == "conditions" then
        return formatConditions(seed)
    elseif mode  == "harvest" then
        return formatHarvestType(seed)
    elseif mode  == "chemicals" then
        return formatChemicals(seed)
    elseif mode  == "mutations" then
        return formatMutations(seed, seedsData)
    else
        return ""
    end
end

return p