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

мНет описания правки
мНет описания правки
(не показаны 374 промежуточные версии этого же участника)
Строка 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 function findResearchByDiscipline(dataCache, discipline)
    return s:gsub('%d+$', '')
     local results = {}
end
     for _, research in ipairs(dataCache) do
 
         if research.technology and research.technology.discipline == discipline then
local function split_first_underscore(k)
            table.insert(results, research.technology)
    local a, b = k:match('^([^_]+)_(.+)$')
    return a, b
end
 
local function collect_labels_from_args(args)
    local meta = {}
     local seen = {}
     for k, v in pairs(args) do
         if type(k) == 'string' and k:find('_', 1, true) then
            local base, rem = split_first_underscore(k)
            if base and rem then
                local label = strip_trailing_digits(rem)
                label = trim(label)
                if label ~= '' then
                    meta[base] = meta[base] or {}
                    if not seen[base] then seen[base] = {} end
                    if not seen[base][label] then
                        table.insert(meta[base], label)
                        seen[base][label] = true
                    end
                end
            end
         end
         end
     end
     end
     return results
     return meta
end
end


-- Таблица для перевода названий дисциплин
local function render_from_args(args)
local disciplineMapping = {
     local field = args[1] or args.field or args["field"]
     Arsenal = "Арсенал",
     local label = args[2] or args.label or args["label"]
     Industrial = "Промышленность",
     field = field and trim(field) or ''
     Experimental = "Экспериментальное",
     label = label and trim(label) or ''
     CivilianServices = "Обслуживание персонала"
}


-- Таблица для цветов по уровням
    -- map base -> label -> value
local tierColors = {
    local map = {}
     [1] = "#54d554",
     for k, v in pairs(args) do
    [2] = "#ed9000",
        if type(k) == 'string' and k:find('_', 1, true) then
    [3] = "#d72a2a"
            local base, rem = split_first_underscore(k)
}
            if base and rem then
 
                local lab = strip_trailing_digits(rem)
function p.main(frame)
                lab = trim(lab)
    -- Подключение CSS
                map[base] = map[base] or {}
    local cssLink = frame:extensionTag('templatestyles', '', {
                local cur = map[base][lab]
        src = 'Шаблон:Research/styles.css'
                if cur then
    })
                    map[base][lab] = cur .. '\n' .. tostring(v)
 
                else
    local dataCache = loadResearchData()
                    map[base][lab] = tostring(v)
    local discipline = frame.args[1] or ""
                end
 
             end
    if discipline and discipline ~= "" then
        -- Инициализация строки вывода
        local out = cssLink .. '<div class="research-group">'
 
        -- Получаем список исследований по дисциплине
        local researches = findResearchByDiscipline(dataCache, discipline)
 
        if #researches == 0 then
             out = out .. '<div style="color:red;">Нет исследований для дисциплины "' .. discipline .. '"</div>'
         end
         end
    end


         for _, tech in ipairs(researches) do
    if field ~= '' and label ~= '' then
            local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
         local base = map[field]
            local tierColor = tierColors[tech.tier] or "#FFFFFF"
        if base then return base[label] or '' end
            local iconPath = tech.icon and tech.icon.sprite or nil
        return ''
    end


            -- Формирование строки prerequisites
    if args[1] and args[2] then
            local prerequisitesStr = ""
        local f = trim(args[1]); local l = trim(args[2])
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
        local base = map[f]
                prerequisitesStr = '<ul>'
        if base then return base[l] or '' end
                for _, prerequisite in ipairs(tech.technologyPrerequisites) do
    end
                    if prerequisite and prerequisite ~= "" then
                        prerequisitesStr = prerequisitesStr .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
                            .. prerequisite .. '.png|' .. prerequisite
                            .. '|Мета=32x32px,link=}}'
                            .. prerequisite .. '</li>'
                    end
                end
                prerequisitesStr = prerequisitesStr .. '</ul>'
            end


            -- Формирование строки unlocks
    return ''
            local unlocksStr = ""
end
            if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
                unlocksStr = '<ul>'
                for _, recipe in ipairs(tech.recipeUnlocks) do
                    if recipe and recipe ~= "" then
                        unlocksStr = unlocksStr .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
                            .. recipe .. '.png|' .. recipe
                            .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'
                            .. recipe .. '}}</li>'
                    end
                end
                unlocksStr = unlocksStr .. '</ul>'
            end


            -- Формируем вывод с использованием шаблона
function p.main(frame)
            out = out .. mw.getCurrentFrame():preprocess(
    local args = frame.args or {}
                '{{Prototypes/Механика/Исследование' ..
    local has_any = false
                '|id=' .. tech.id ..
    for k, _ in pairs(args) do
                '|icon=' .. iconPath ..
         has_any = true; break
                '|name=' .. tech.name ..
                '|discipline=' .. tech.discipline ..
                '|tier=' .. tech.tier ..
                '|tierColor=' .. tierColor ..
                '|disciplineName=' .. disciplineName ..
                '|cost=' .. tech.cost ..
                '|prerequisites=' .. prerequisitesStr ..
                '|unlocks=' .. unlocksStr ..
                '}}')
         end
       
        return out
    else
        return cssLink .. '<div style="color:red;">Дисциплина "' .. discipline .. '" не найдена.</div>'
     end
     end
    if not has_any then return collect_labels_from_args(args) end
    return render_from_args(args)
end
end


return p
return p