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

Нет описания правки
мНет описания правки
(не показаны 373 промежуточные версии этого же участника)
Строка 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 = {}
    for _, research in ipairs(dataCache) do
        if research.technology and research.technology.discipline == discipline then
            table.insert(results, research.technology)
        end
    end
    return results
end
end


-- Таблица для перевода названий дисциплин
local function split_first_underscore(k)
local disciplineMapping = {
     local a, b = k:match('^([^_]+)_(.+)$')
     Arsenal = "Арсенал",
     return a, b
    Industrial = "Промышленность",
end
     Experimental = "Экспериментальное",
    CivilianServices = "Обслуживание персонала"
}


-- Таблица для цветов по уровням
local function collect_labels_from_args(args)
local tierColors = {
    local meta = {}
     [1] = "#54d554",
     local seen = {}
     [2] = "#ed9000",
     for k, v in pairs(args) do
    [3] = "#d72a2a"
        if type(k) == 'string' and k:find('_', 1, true) then
}
            local base, rem = split_first_underscore(k)
 
            if base and rem then
function p.main(frame)
                local label = strip_trailing_digits(rem)
    -- Подключение CSS
                label = trim(label)
    local cssLink = frame:extensionTag('templatestyles', '', {
                if label ~= '' then
        src = 'Шаблон:Research/styles.css'
                    meta[base] = meta[base] or {}
    })
                    if not seen[base] then seen[base] = {} end
 
                     if not seen[base][label] then
    local dataCache = loadResearchData()
                         table.insert(meta[base], label)
    local discipline = frame.args[1] or ""
                        seen[base][label] = true
 
    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
 
        for _, tech in ipairs(researches) do
            local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
            local tierColor = tierColors[tech.tier] or "#FFFFFF"
            local iconPath = tech.icon and tech.icon.sprite or nil
 
            -- Формирование строки prerequisites
            local prerequisitesStr = ""
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
                prerequisitesStr = '<ul>'
                for _, prerequisite in ipairs(tech.technologyPrerequisites) do
                     if prerequisite and prerequisite ~= "" then  
                         prerequisitesStr = prerequisitesStr .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
                            .. prerequisite .. '.png|' .. prerequisite
                            .. '|Мета=32x32px,link=}}'
                            .. prerequisite .. '</li>'
                     end
                     end
                 end
                 end
                prerequisitesStr = prerequisitesStr .. '</ul>'
             end
             end
        end
    end
    return meta
end
local function render_from_args(args)
    local field = args[1] or args.field or args["field"]
    local label = args[2] or args.label or args["label"]
    field = field and trim(field) or ''
    label = label and trim(label) or ''


            -- Формирование строки unlocks
    -- map base -> label -> value
             local unlocksStr = ""
    local map = {}
             if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
    for k, v in pairs(args) do
                 unlocksStr = '<ul>'
        if type(k) == 'string' and k:find('_', 1, true) then
                 for _, recipe in ipairs(tech.recipeUnlocks) do
             local base, rem = split_first_underscore(k)
                    if recipe and recipe ~= "" then  
             if base and rem then
                        unlocksStr = unlocksStr .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'  
                 local lab = strip_trailing_digits(rem)
                            .. recipe .. '.png|' .. recipe
                 lab = trim(lab)
                            .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'
                map[base] = map[base] or {}
                            .. recipe .. '}}</li>'
                local cur = map[base][lab]
                     end
                if cur then
                    map[base][lab] = cur .. '\n' .. tostring(v)
                else
                     map[base][lab] = tostring(v)
                 end
                 end
                unlocksStr = unlocksStr .. '</ul>'
             end
             end
         end
         end
     end
     end


     -- Формируем вывод с использованием шаблона
     if field ~= '' and label ~= '' then
    return mw.getCurrentFrame():preprocess(
         local base = map[field]
    '{{Prototypes/Механика/Исследование' ..
         if base then return base[label] or '' end
    '|id=' .. tech.id ..
         return ''
         '|icon=' .. iconPath ..
    end
         '|name=' .. tech.name ..
 
         '|discipline=' .. tech.discipline ..
    if args[1] and args[2] then
         '|tier=' .. tech.tier ..
         local f = trim(args[1]); local l = trim(args[2])
         '|tierColor=' .. tierColor ..
         local base = map[f]
         '|disciplineName=' .. disciplineName ..
         if base then return base[l] or '' end
        '|cost=' .. tech.cost ..
    end
        '|prerequisites=' .. prerequisitesStr ..
 
         '|unlocks=' .. unlocksStr ..
    return ''
        '}}'
end
     )
 
function p.main(frame)
    local args = frame.args or {}
    local has_any = false
    for k, _ in pairs(args) do
         has_any = true; break
    end
    if not has_any then return collect_labels_from_args(args) end
 
     return render_from_args(args)
end
end


return p
return p