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

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


-- Загрузка данных
local function trim(s)
local function loadData(filePath)
     if not s then return s end
     local page = mw.title.new(filePath)
     return (s:gsub('^%s*(.-)%s*$', '%1'))
     local content = page and page:getContent()
    return content and mw.text.jsonDecode(content) or nil
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)
                lab = trim(lab)
                map[base] = map[base] or {}
                local cur = map[base][lab]
                if cur then
                    map[base][lab] = cur .. '\n' .. tostring(v)
                else
                    map[base][lab] = tostring(v)
                end
            end
        end
    end


-- Универсальная функция для генерации списков
    if field ~= '' and label ~= '' then
local function generateTemplate(list, templateType)
        local base = map[field]
    if not list or #list == 0 then
        if base then return base[label] or '' end
         return ""
         return ''
     end
     end


     local result = "<ul>"
     if args[1] and args[2] then
    for _, entry in ipairs(list) do
        local f = trim(args[1]); local l = trim(args[2])
         if entry and entry ~= "" then
         local base = map[f]
            if templateType == "prerequisite" then
        if base then return base[l] or '' end
                result = result .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
                    .. entry .. '.png|' .. entry
                    .. '|Мета=32x32px,link=}} '
                    .. entry .. '</li>'
            elseif templateType == "unlock" then
                result = result .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
                    .. entry .. '.png|' .. entry
                    .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'
                    .. entry .. '}}</li>'
            end
        end
     end
     end
    result = result .. "</ul>"


     return result
     return ''
end
end


function p.main(frame)
function p.main(frame)
    -- Подключение CSS
     local args = frame.args or {}
     local cssLink = frame:extensionTag('templatestyles', '', {
    local field = args[1]
        src = 'Шаблон:Research/styles.css'
    })


     local dataCache = loadData("User:IanComradeBot/Песочница.json")
     if field == "meta" then
    if not data or type(data) ~= 'table' then
        local meta = collect_labels_from_args(args)
         return 'Ошибка: Невозможно загрузить данные из JSON.'
         return mw.text.jsonEncode(meta)
     end
     end
   
    local discipline = frame.args[1] or ""


     if discipline and discipline ~= "" then
     return render_from_args(args)
        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 и unlocks
            local prerequisitesStr = generateTemplate(tech.technologyPrerequisites, "prerequisite")
            local unlocksStr = generateTemplate(tech.recipeUnlocks, "unlock")
 
            -- Формируем вывод с использованием шаблона
            out = out .. mw.getCurrentFrame():preprocess(
                '{{Prototypes/Механика/Исследование' ..
                '|id=' .. tech.id ..
                '|icon=' .. iconPath ..
                '|name=' .. tech.name ..
                '|discipline=' .. tech.discipline ..
                '|tier=' .. tech.tier ..
                '|tierColor=' .. tierColor ..
                '|disciplineName=' .. disciplineName ..
                '|cost=' .. tech.cost ..
                '|prerequisites=' .. prerequisitesStr ..
                '|unlocks=' .. unlocksStr ..
                '}}'
            )
        end
 
        out = out .. '</div>'
        return out
    else
        return cssLink .. '<div style="color:red;">Дисциплина "' .. discipline .. '" не найдена.</div>'
    end
end
end


return p
return p