Модуль:Prototypes/Механика/Исследование: различия между версиями

мНет описания правки
мНет описания правки
 
(не показано 19 промежуточных версий этого же участника)
Строка 1: Строка 1:
-- Загрузка данных
local recipeData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local p = {}
local p = {}


-- Функция для загрузки данных исследований из JSON-файла
-- Функция для загрузки данных исследований из JSON-файла
local function loadResearchData()
local function loadResearchData()
     return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/research_prototypes.json"):getContent())
     return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/research.json"):getContent())
end
 
-- Кэш для ID машин
local machineIDCache = {}
 
-- Функция для поиска данных по ID
local function findResearchById(dataCache, id)
    for _, tech in ipairs(dataCache) do
        if tech.id == id then
            return tech
        end
    end
    return nil
end
 
-- Функция для перевода ID плат в ID машин
local function translateBoardIDToMachineID(boardID)
    if machineIDCache[boardID] then
        return machineIDCache[boardID]
    end
 
    local data = mw.text.jsonDecode(mw.title.new("User:IanComradeBot/entity_prototypes.json"):getContent())
    local board = data[boardID]
    if not board or not board.name then
        return nil
    end
 
    if not board.name:find("%(машинная плата%)") and not board.name:find("%(консольная плата%)") then
        return nil
    end
 
    local machineName = board.name:gsub(" %(машинная плата%)", ""):gsub(" %(консольная плата%)", "")
    local excludeWords = {"Unanchored", "Debug", "Admin", "Enabled"}
 
    for _, entity in pairs(data) do
        if entity.name == machineName then
            local shouldExclude = false
            for _, word in ipairs(excludeWords) do
                if entity.id:find(word) then
                    shouldExclude = true
                    break
                end
            end
 
            if not shouldExclude then
                machineIDCache[boardID] = entity.id
                return entity.id
            end
        end
    end
 
    return nil
end
end


Строка 66: Строка 17:
}
}


-- Таблица для цветов по уровню
-- Таблица для цветов по уровням
local tierColors = {
local tierColors = {
     [1] = "#54d554",
     [1] = "#54d554",
Строка 74: Строка 25:


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


     local dataCache = loadResearchData()
     -- Получаем ID и иконку из параметров
     local id = frame.args.id or ""
     local researchId = frame.args[1] or ""
     local icon = frame.args.icon or ""
     local icon = frame.args[2] or ""
    local customRecipeUnlocks = frame.args.customRecipeUnlocks or nil
 
    if researchId and researchId ~= "" then
        local out = ""
 
        -- Поиск исследования по ID
        local tech = nil
        for _, research in ipairs(dataCache) do
            if research and research.id == researchId then
                tech = research
                break
            end
        end
 
        if not tech then
            out = out .. '<div style="color:red;">Исследование с ID "' .. researchId .. '" не найдено.</div>'
        else
            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 tech = findResearchById(dataCache, id)
            -- Формирование строки необходимых исследований
    if not tech then
            local prerequisites = ""
        return cssLink .. '<div style="color:red;">Нет доступных исследований.</div>'
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
    end
                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 and research.id == prerequisiteId then
                                prerequisiteName = research.name
                                break
                            end
                        end


    local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
                        -- Если название найдено, выводим его
    local tierColor = tierColors[tech.tier] or "#FFFFFF"
                        if prerequisiteName ~= "" then
                            prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|'.. prerequisiteName .. '}}</li>'
                        end
                    end
                end
                prerequisites = prerequisites .. '</ul>'
            end


    local out = cssLink .. '<div class="research" id="' .. tech.discipline .. '">'
            -- Формирование строки открываемых исследований
    out = out .. '<div class="research__images">[[Файл:' .. icon .. '.png|64x64px|центр|link=]]</div>'
local unlocks = ""
    out = out .. '<div class="research__name">' .. tech.name .. '[[Файл:' .. tech.discipline .. '.png|16px|link=]]</div>'
if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
    out = out .. '<div class="research__type">'
    unlocks = '<ul>'
    out = out .. '<div>Уровень: <span style="color:' .. tierColor .. ';">' .. tech.tier .. '</span></div>'
    for _, recipeId in ipairs(tech.recipeUnlocks) do
    out = out .. '<div class="research__technology">' .. disciplineName .. '</div>'
        if recipeId and recipeId ~= "" then
    out = out .. '<div>Стоимость: <span style="color:#DA70D6;">' .. tech.cost .. '</span></div>'
            -- Ищем в recipeData объект с id == recipeId
    out = out .. '</div>'
            local newId = recipeId
    out = out .. '<div class="research__unblocks">Разблокирует:'
            for _, rec in ipairs(recipeData) do
    out = out .. '<ul>'
                if rec and rec.id == recipeId then
                    newId = rec.result or recipeId
                    break
                end
            end
            unlocks = unlocks .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'  
                .. newId .. '.png|' .. newId
                .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'  
                .. newId .. '}}</li>'
        end
    end
    unlocks = unlocks .. '</ul>'
end


    local recipeUnlocks = customRecipeUnlocks and mw.text.split(customRecipeUnlocks, " ") or tech.recipeUnlocks
            -- Шаблон для отображения блока исследования
    for _, recipe in ipairs(recipeUnlocks) do
            local templateArgs = {
        local machineID = translateBoardIDToMachineID(recipe) or recipe
                id = tech.id,
        out = out .. frame:preprocess('<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:' .. machineID .. '.png|' .. machineID .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|' .. machineID .. '}}</li>')
                icon = iconPath,
    end
                name = tech.name,
                discipline = tech.discipline,
                tier = tech.tier,
                tierColor = tierColor,
                disciplineName = disciplineName,
                cost = tech.cost,
                unlocks = unlocks
            }


    out = out .. '</ul>'
            -- Добавление prerequisites только если он существует
    out = out .. '</div>'
            if prerequisites ~= "" then
    out = out .. '</div>'
                templateArgs.prerequisites = prerequisites
            end


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


return p
return p