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

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


-- Функция для загрузки данных исследований из JSON-файла
local function trim(s)
local function loadResearchData()
     if not s then return s end
     return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/Песочница.json"):getContent())
    return (s:gsub('^%s*(.-)%s*$', '%1'))
end
end


-- Таблица для перевода названий дисциплин
local function strip_trailing_digits(s)
local disciplineMapping = {
     return s:gsub('%d+$', '')
     Arsenal = "Арсенал",
end
    Industrial = "Промышленность",
    Experimental = "Экспериментальное",
    CivilianServices = "Обслуживание персонала"
}


-- Таблица для цветов по уровням
local function split_first_underscore(k)
local tierColors = {
    local a, b = k:match('^([^_]+)_(.+)$')
    [1] = "#54d554",
     return a, b
     [2] = "#ed9000",
end
    [3] = "#d72a2a"
}


function p.main(frame)
local function collect_labels_from_args(args)
     local dataCache = loadResearchData()
     local meta = {}
 
     local seen = {}
    -- Получаем ID и иконку из параметров
     for k, v in pairs(args) do
     local researchId = frame.args[1] or ""
        if type(k) == 'string' and k:find('_', 1, true) then
     local icon = frame.args[2] or ""
            local base, rem = split_first_underscore(k)
 
            if base and rem then
    if researchId and researchId ~= "" then
                local label = strip_trailing_digits(rem)
        local out
                label = trim(label)
 
                if label ~= '' then
        -- Поиск исследования по ID
                    meta[base] = meta[base] or {}
        local tech = nil
                    if not seen[base] then seen[base] = {} end
        for _, research in ipairs(dataCache) do
                    if not seen[base][label] then
            if research.technology and research.technology.id == researchId then
                        table.insert(meta[base], label)
                tech = research.technology
                        seen[base][label] = true
                 break
                    end
                 end
             end
             end
         end
         end
    end
    return meta
end


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


            -- Формирование строки необходимых исследований
    -- map base -> label -> value
            local prerequisites = ""
    local map = {}
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
    for k, v in pairs(args) do
                prerequisites = '<ul>'
        if type(k) == 'string' and k:find('_', 1, true) then
                for _, prerequisiteId in ipairs(tech.technologyPrerequisites) do
            local base, rem = split_first_underscore(k)
                    if prerequisiteId and prerequisiteId ~= "" then  
            if base and rem then
                        -- Находим название исследования по ID
                local lab = strip_trailing_digits(rem)
                        local prerequisiteName = ""
                lab = trim(lab)
                        for _, research in ipairs(dataCache) do
                map[base] = map[base] or {}
                            if research.technology and research.technology.id == prerequisiteId then
                local cur = map[base][lab]
                                prerequisiteName = research.technology.name
                if cur then
                                break
                    map[base][lab] = cur .. '\n' .. tostring(v)
                            end
                else
                        end
                     map[base][lab] = tostring(v)
 
                        -- Если название найдено, выводим его
                        if prerequisiteName ~= "" then
                            prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|'.. prerequisiteName .. '}}</li>'
                        end
                     end
                 end
                 end
                prerequisites = prerequisites .. '</ul>'
             end
             end
        end
    end
    if field ~= '' and label ~= '' then
        local base = map[field]
        if base then return base[label] or '' end
        return ''
    end


            -- Формирование строки открываемых исследований
    if args[1] and args[2] then
            local unlocks = ""
        local f = trim(args[1]); local l = trim(args[2])
            if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
        local base = map[f]
                unlocks = '<ul>'
        if base then return base[l] or '' end
                for _, recipe in ipairs(tech.recipeUnlocks) do
    end
                    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


            -- Шаблон для отображения блока исследования
    return ''
            local templateArgs = {
end
                id = tech.id,
                icon = iconPath,
                name = tech.name,
                discipline = tech.discipline,
                tier = tech.tier,
                tierColor = tierColor,
                disciplineName = disciplineName,
                cost = tech.cost,
                unlocks = unlocks
            }


            -- Добавление prerequisites только если он существует
function p.main(frame)
            if prerequisites ~= "" then
    local args = frame.args or {}
                templateArgs.prerequisites = prerequisites
    local field = args[1]
            end


            out = out .. frame:expandTemplate({
    if field == "meta" then
                title = 'Prototypes/Механика/Исследование',
        local meta = collect_labels_from_args(args)
                args = templateArgs
         return mw.text.jsonEncode(meta)
            })
end
         return mw.getCurrentFrame():preprocess(out)
    else
        return '<div style="color:red;">Не указан ID исследования.</div>'
     end
     end
    return render_from_args(args)
end
end


return p
return p