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

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


-----------------------------------------------------------
function p.main(frame)
-- Загрузка данных
     local args = getArgs(frame, { removeBlanks = false })
-----------------------------------------------------------
    local name = args[1] or ""
local latheData      = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
    local attributes = args[2] or ""
local recipeData     = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
     if name == "" then
local recipePackData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipe pack.json/data")
         return "<span class=\"error\">Ошибка: не указано имя файла.</span>"
local researchData  = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
local materialData  = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
local chemData      = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
 
-----------------------------------------------------------
-- Вспомогательные функции
-----------------------------------------------------------
local function sortRecipesByPriority(recipes)
    table.sort(recipes, function(a, b)
        local priority = { Static = 1, EMAG = 3 }
        local aPriority = priority[a.discipline] or 2
        local bPriority = priority[b.discipline] or 2
 
        if a.isEmag ~= b.isEmag then
            return not a.isEmag
        end
 
        if aPriority == bPriority then
            if a.tier == b.tier then
                return a.discipline < b.discipline
            end
            return a.tier < b.tier
        end
 
        return aPriority < bPriority
    end)
end
 
local function getRecipeDetails(recipeId)
    for _, recipe in ipairs(recipeData) do
        if recipe.id == recipeId then
            return recipe
        end
    end
    return nil
end
 
local function findInResearch(recipeId)
     for _, research in ipairs(researchData) do
        if research and research.recipeUnlocks then
            for _, unlock in ipairs(research.recipeUnlocks) do
                if unlock == recipeId then
                    return {
                        name = research.name,
                        tier = research.tier,
                        discipline = research.discipline
                    }
                end
            end
        end
    end
    return nil
end
 
local function getRecipePackDetails(packId)
    for _, pack in ipairs(recipePackData) do
        if pack.id == packId then
            return pack
         end
    end
    return nil
end
 
-----------------------------------------------------------
-- Функция для сбора рецептов из станка
-----------------------------------------------------------
local function getLatheRecipes(lathe)
    local recipes = {}
    local chemMapping = {}
    for id, chem in pairs(chemData) do
        chemMapping[id] = chem.name
     end
     end
    local ext = (args["ext"] or "png"):gsub("^%.", "")
    local namespace = args["namespace"] or "Файл"
    local max = tonumber(args["max"]) or 50
    local include_base = (args["base"] ~= "no")


-- Вспомогательная функция для обработки одного рецепта
     local found = {}
local function processRecipe(recipeId, defaultDiscipline, isEmag)
    local recipe = getRecipeDetails(recipeId)
    if recipe then
        if recipe.result then
            local info = {
                id = recipe.id,
                result = recipe.result,
                completetime = recipe.completetime,
                materials = recipe.materials,
                discipline = defaultDiscipline,
                tier = 0,
                isEmag = isEmag or false
            }
            if defaultDiscipline ~= "Static" then
                local researchInfo = findInResearch(recipeId)
                if researchInfo then
                    info.discipline = researchInfo.discipline
                    info.tier = researchInfo.tier
                    info.researchName = researchInfo.name
                end
            end
            table.insert(recipes, info)
        elseif recipe.resultReagents then
            for reagent, amount in pairs(recipe.resultReagents) do
                local reagentName = chemMapping[reagent] or reagent
                table.insert(recipes, {
                    id = recipe.id,
                    result = reagentName .. "|amount=" .. amount .. "ед.|mode-chem=1",
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = defaultDiscipline,
                    tier = 0,
                    isEmag = isEmag or false
                })
                break
            end
        end
    end
end
 
    -- Обработка рецептов для lathe.Lathe (старый и новый формат)
     if lathe.Lathe then
        if lathe.Lathe.staticRecipes then
            for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
                processRecipe(recipeId, "Static", false)
            end
        end
        if lathe.Lathe.dynamicRecipes then
            for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
                processRecipe(recipeId, "Dynamic", false)
            end
        end
        if lathe.Lathe.staticPacks then
            for _, packId in ipairs(lathe.Lathe.staticPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Static", false)
                    end
                end
            end
        end
        if lathe.Lathe.dynamicPacks then
            for _, packId in ipairs(lathe.Lathe.dynamicPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Dynamic", false)
                    end
                end
            end
        end
    end


     if lathe.EmagLatheRecipes then
     if include_base then
         if lathe.EmagLatheRecipes.emagStaticRecipes then
         local t = mw.title.new("Файл:" .. name .. "." .. ext)
            for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
         if t and t.exists then
                processRecipe(recipeId, "Static", true)
             table.insert(found, "")
            end
        end
        if lathe.EmagLatheRecipes.emagDynamicRecipes then
            for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
                processRecipe(recipeId, "Dynamic", true)
            end
        end
        if lathe.EmagLatheRecipes.emagStaticPacks then
            for _, packId in ipairs(lathe.EmagLatheRecipes.emagStaticPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Static", true)
                    end
                end
            end
        end
         if lathe.EmagLatheRecipes.emagDynamicPacks then
             for _, packId in ipairs(lathe.EmagLatheRecipes.emagDynamicPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Dynamic", true)
                    end
                end
            end
         end
         end
     end
     end


     sortRecipesByPriority(recipes)
     for i = 1, max do
    return recipes
         local t = mw.title.new("Файл:" .. name .. "-" .. i .. "." .. ext)
end
        if t and t.exists then
 
             table.insert(found, "-" .. i)
-----------------------------------------------------------
-- Общие таблицы для форматирования вывода
-----------------------------------------------------------
local disciplineMapping = {
    Arsenal = "Арсенал",
    Industrial = "Промышленность",
    Experimental = "Экспериментальное",
    CivilianServices = "Обслуживание персонала"
}
local tierColors = {
    [1] = "#54d554",
    [2] = "#ed9000",
    [3] = "#d72a2a"
}
local materialMappingGlobal = {}
for _, material in ipairs(materialData) do
    if material.id then
         materialMappingGlobal[material.id] = material.stackEntity or material.id or material.name
    end
end
 
-----------------------------------------------------------
-- Функция для формирования строки рецепта
-----------------------------------------------------------
local function formatRecipe(recipe, timeMultiplier, materialUseMultiplier, itemMode)
    local out = ""
    local scaledTime = recipe.completetime * timeMultiplier
    out = out .. '{{Шаблон:Prototypes/Машина/Станок|product=' .. recipe.result
    if itemMode then
        out = out .. '|no-product=1'
    end
    out = out .. '|complete-time={{#invoke:Code/Формат/Время|main|seconds|' .. scaledTime .. '}}|materials='
 
    if recipe.materials then
        local materialEntries = {}
        for material, amount in pairs(recipe.materials) do
            local stackEntity = materialMappingGlobal[material] or material
            local scaledAmount = (amount * materialUseMultiplier) / 100
             table.insert(materialEntries, string.format('<b>[[File:%s.png|32x32px|link=]] %g {{#invoke:Entity Lookup|getname|%s}}</b>', stackEntity, scaledAmount, stackEntity))
         end
         end
        out = out .. table.concat(materialEntries)
    else
        out = out .. 'Нет данных о материалах'
    end
    if recipe.discipline ~= "Static" then
        local tierColor = tierColors[recipe.tier] or "#FFFFFF"
        local disciplineName = disciplineMapping[recipe.discipline] or "Неизвестная дисциплина"
        out = out .. '|info=<div style="font-weight:600;"><span style="margin:8px;">[[File:' .. recipe.discipline .. '.png|16x16px|link=]]</span> [[Руководство по исследованию и разработке|' .. disciplineName
        out = out .. ']], уровень: <span style="color: ' .. tierColor .. '">' .. recipe.tier .. '</span> </div>'
     end
     end


     if recipe.isEmag then
     if #found == 0 then
         out = out .. '|mode-emag=1'
         return ""
     end
     end


     if recipe.discipline ~= "Static" then
     local before = "[[" .. namespace .. ":" .. name
        out = out .. '|mode-research=1'
     local after = "." .. ext .. "|" .. attributes .. "]]"
    end
 
    out = out .. '}}'
    return out
end
 
-----------------------------------------------------------
-- Функция для поиска и вывода рецептов по ID станка
-----------------------------------------------------------
function p.lathe(frame)
    local latheId = frame.args[1] or ""
    if latheId == "" then
        return '<div style="color:red;">Не указан ID станка.</div>'
    end
 
    local lathe = nil
    for _, data in ipairs(latheData) do
        if data.id == latheId then
            lathe = data
            break
        end
    end
 
    if not lathe then
        return '<div style="color:red;">Станок с ID "' .. latheId .. '" не найден.</div>'
    end
 
    local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
    local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
    local recipes = getLatheRecipes(lathe)
    local out = ""
    for _, recipe in ipairs(recipes) do
        out = out .. formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
    end
 
    return mw.getCurrentFrame():preprocess(out)
end
 
-----------------------------------------------------------
-- Функция для поиска и вывода рецептов по ID предмета
-----------------------------------------------------------
function p.item(frame)
    local itemId = frame.args[1] or ""
    if itemId == "" then
        return '<div style="color:red;">Не указан ID предмета.</div>'
    end
 
    local out = '{| class="wikitable"' .. "\n! Станок ID\n! Рецепт\n"
     local foundAny = false
 
    for _, lathe in ipairs(latheData) do
        local recipes = getLatheRecipes(lathe)
        local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
        local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
 
        for _, recipe in ipairs(recipes) do
            if recipe.id == itemId or recipe.result == itemId then
                foundAny = true
                out = out .. '|-' .. "\n"
                out = out .. '| [[File:' .. lathe.id .. '.png|32x32px|link=]] [[{{#invoke:Entity Lookup|getname|' .. lathe.id .. '}}|{{#invoke:Entity Lookup|getname|' .. lathe.id .. '}}]]' .. "\n"
                out = out .. '| ' .. formatRecipe(recipe, timeMultiplier, materialUseMultiplier, true) .. "\n"
            end
        end
    end
 
    if not foundAny then
        return '<div style="color:red;">Рецепт для предмета с ID "' .. itemId .. '" не найден во всех станках.</div>'
    end
 
    out = out .. '|}'
    return mw.getCurrentFrame():preprocess(out)
end
 
-----------------------------------------------------------
-- Функция для поиска и вывода рецептов по ID материала
-----------------------------------------------------------
function p.material(frame)
    local materialId = frame.args[1] or ""
    if materialId == "" then
        return '<div style="color:red;">Не указан ID материала.</div>'
    end
 
    local out = '{| class="wikitable" style="text-align: center;"' .. "\n! Станок\n! Рецепт\n"
    local foundAny = false
 
    for _, lathe in ipairs(latheData) do
        local recipes = getLatheRecipes(lathe)
        local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
        local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
        local matchingRecipes = {}
 
        for _, recipe in ipairs(recipes) do
            if recipe.materials then
                for matId, _ in pairs(recipe.materials) do
                    if matId == materialId then
                        table.insert(matchingRecipes, recipe)
                        break
                    end
                end
            end
        end
 
        if #matchingRecipes > 0 then
            foundAny = true
            local rowspan = #matchingRecipes
            for i, recipe in ipairs(matchingRecipes) do
                out = out .. '|-' .. "\n"
                if i == 1 then
                    out = out .. string.format('| rowspan="%d" [[File:%s.png|32x32px|link=]] [[{{#invoke:Entity Lookup|getname|%s}}|{{#invoke:Entity Lookup|getname|%s}}]]' .. "\n", rowspan, lathe.id, lathe.id, lathe.id)
                end
                local recipeName = recipe.researchName or recipe.result
                local recipeText = '<b>' .. recipeName .. '</b><br/>' .. formatRecipe(recipe, timeMultiplier, materialUseMultiplier, true)
                out = out .. '| ' .. recipeText .. "\n"
            end
        end
    end


     if not foundAny then
     local parts = {}
        return '<div style="color:red;">Для материала с ID "' .. materialId .. '" рецептов не найдено во всех станках.</div>'
    table.insert(parts, "<choose before=\"" .. before .. "\" after=\"" .. after .. "\">")
    for _, suf in ipairs(found) do
        table.insert(parts, "<option>" .. suf .. "</option>")
     end
     end
    table.insert(parts, "</choose>")


    out = out .. '|}'
     return frame:preprocess(table.concat(parts, "\n"))
     return mw.getCurrentFrame():preprocess(out)
end
end


return p
return p

Текущая версия от 02:52, 17 марта 2026

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

local p = {}
local getArgs = require('Module:Arguments').getArgs

function p.main(frame)
    local args = getArgs(frame, { removeBlanks = false })
    local name = args[1] or ""
    local attributes = args[2] or ""
    if name == "" then
        return "<span class=\"error\">Ошибка: не указано имя файла.</span>"
    end
    local ext = (args["ext"] or "png"):gsub("^%.", "") 
    local namespace = args["namespace"] or "Файл"
    local max = tonumber(args["max"]) or 50
    local include_base = (args["base"] ~= "no")

    local found = {}

    if include_base then
        local t = mw.title.new("Файл:" .. name .. "." .. ext)
        if t and t.exists then
            table.insert(found, "")
        end
    end

    for i = 1, max do
        local t = mw.title.new("Файл:" .. name .. "-" .. i .. "." .. ext)
        if t and t.exists then
            table.insert(found, "-" .. i)
        end
    end

    if #found == 0 then
        return ""
    end

    local before = "[[" .. namespace .. ":" .. name
    local after = "." .. ext .. "|" .. attributes .. "]]"

    local parts = {}
    table.insert(parts, "<choose before=\"" .. before .. "\" after=\"" .. after .. "\">")
    for _, suf in ipairs(found) do
        table.insert(parts, "<option>" .. suf .. "</option>")
    end
    table.insert(parts, "</choose>")

    return frame:preprocess(table.concat(parts, "\n"))
end

return p