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

мНет описания правки
Нет описания правки
 
(не показано 367 промежуточных версий этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}
 
local getArgs = require('Module:Arguments').getArgs
-- Функция для загрузки данных исследований из JSON-файла
local function loadResearchData()
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/Песочница.json"):getContent())
end
 
-- Таблица для перевода названий дисциплин
local disciplineMapping = {
    Arsenal = "Арсенал",
    Industrial = "Промышленность",
    Experimental = "Экспериментальное",
    CivilianServices = "Обслуживание персонала"
}
 
-- Таблица для цветов по уровням
local tierColors = {
    [1] = "#54d554",
    [2] = "#ed9000",
    [3] = "#d72a2a"
}


function p.main(frame)
function p.main(frame)
    -- Подключение CSS
     local args = getArgs(frame, { removeBlanks = false })
     local cssLink = frame:extensionTag('templatestyles', '', {
    local name = args[1] or ""
         src = 'Шаблон:Research/styles.css'
    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 dataCache = loadResearchData()
     local found = {}


     -- Получаем ID и иконку из параметров
     if include_base then
    local researchId = frame.args[1] or ""
        local t = mw.title.new("Файл:" .. name .. "." .. ext)
    local icon = frame.args[2] or ""
        if t and t.exists then
 
            table.insert(found, "")
    if researchId and researchId ~= "" then
        end
        local out = cssLink .. '<div class="research-group">'
    end


        -- Поиск исследования по ID
    for i = 1, max do
         local tech = nil
         local t = mw.title.new("Файл:" .. name .. "-" .. i .. "." .. ext)
        for _, research in ipairs(dataCache) do
        if t and t.exists then
            if research.technology and research.technology.id == researchId then
            table.insert(found, "-" .. i)
                tech = research.technology
                break
            end
         end
         end
    end


        if not tech then
    if #found == 0 then
            out = out .. '<div style="color:red;">Исследование с ID "' .. researchId .. '" не найдено.</div>'
         return ""
         else
    end
            local tierColor = tierColors[tech.tier] or "#FFFFFF"
            local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
            local iconPath = icon ~= "" and icon or (tech.icon and tech.icon.sprite or nil)


            -- Формирование строки необходимых исследований
    local before = "[[" .. namespace .. ":" .. name
            local prerequisites = ""
    local after = "." .. ext .. "|" .. attributes .. "]]"
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
                prerequisites = '<ul>'
                for _, prerequisiteId in ipairs(tech.technologyPrerequisites) do
                    if prerequisiteId and prerequisiteId ~= "" then
                        -- Находим название исследования по ID
                        local prerequisiteName = ""
                        for _, research in ipairs(dataCache) do
                            if research.technology and research.technology.id == prerequisiteId then
                                prerequisiteName = research.technology.name
                                break
                            end
                        end


                        -- Если название найдено, выводим его
    local parts = {}
                        if prerequisiteName ~= "" then
    table.insert(parts, "<choose before=\"" .. before .. "\" after=\"" .. after .. "\">")
                            prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|'.. prerequisiteName .. '}}</li>'
    for _, suf in ipairs(found) do
                        end
        table.insert(parts, "<option>" .. suf .. "</option>")
                    end
    end
                end
    table.insert(parts, "</choose>")
                prerequisites = prerequisites .. '</ul>'
            end


            -- Формирование строки открываемых исследований
    return frame:preprocess(table.concat(parts, "\n"))
            local unlocks = ""
            if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
                unlocks = '<ul>'
                for _, recipe in ipairs(tech.recipeUnlocks) do
                    if recipe and recipe ~= "" then
                        unlocks = unlocks .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
                            .. recipe .. '.png|' .. recipe
                            .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'
                            .. recipe .. '}}</li>'
                    end
                end
                unlocks = unlocks .. '</ul>'
            end
 
            -- Шаблон для отображения блока исследования
            local templateArgs = {
                id = tech.id,
                icon = iconPath,
                name = tech.name,
                discipline = tech.discipline,
                tier = tech.tier,
                tierColor = tierColor,
                disciplineName = disciplineName,  
                cost = tech.cost,
                unlocks = unlocks
            }
 
            -- Добавление prerequisites только если он существует
            if prerequisites ~= "" then
                templateArgs.prerequisites = prerequisites
            end
 
            out = out .. frame:expandTemplate({
                title = 'Prototypes/Механика/Исследование',
                args = templateArgs
            })
end
        return mw.getCurrentFrame():preprocess(out)
    else
        return cssLink .. '<div style="color:red;">Не указан ID исследования.</div>'
    end
end
end


return p
return p