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

мНет описания правки
мНет описания правки
 
(не показано 6 промежуточных версий этого же участника)
Строка 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 function findResearchById(dataCache, id)
for _, research in ipairs(dataCache) do
if research.id == id then
return research
end
end
return nil
end
 
-- Кэш для ID машин
local machineIDCache = {}
 
-- Функция для перевода 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


-- Таблица для перевода названий дисциплин
-- Таблица для перевода названий дисциплин
local disciplineMapping = {
local disciplineMapping = {
Arsenal = "Арсенал",
    Arsenal = "Арсенал",
Industrial = "Промышленность",
    Industrial = "Промышленность",
Experimental = "Экспериментальное",
    Experimental = "Экспериментальное",
CivilianServices = "Обслуживание персонала"
    CivilianServices = "Обслуживание персонала"
}
}


-- Таблица для цветов по уровню
-- Таблица для цветов по уровням
local tierColors = {
local tierColors = {
[1] = "#54d554",
    [1] = "#54d554",
[2] = "#ed9000",
    [2] = "#ed9000",
[3] = "#d72a2a"
    [3] = "#d72a2a"
}
}


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 ""


-- Получение кастомных рецептов с индексами (если они есть)
    if researchId and researchId ~= "" then
local customRecipeUnlocks = {}
        local out = ""
for i = 1, 100 do
local indexKey = "customRecipeUnlocksIndex" .. i
if frame.args[indexKey] then
table.insert(customRecipeUnlocks, frame.args[indexKey])
end
end


-- Получение кастомных рецептов без индексации
        -- Поиск исследования по ID
if frame.args.customRecipeUnlocks then
        local tech = nil
local tempUnlocks = mw.text.split(frame.args.customRecipeUnlocks, " ")
        for _, research in ipairs(dataCache) do
for _, item in ipairs(tempUnlocks) do
            if research and research.id == researchId then
table.insert(customRecipeUnlocks, item)
                tech = research
end
                break
end
            end
        end


local tech = findResearchById(dataCache, id)
        if not tech then
if not tech then
            out = out .. '<div style="color:red;">Исследование с ID "' .. researchId .. '" не найдено.</div>'
return cssLink .. '<div style="color:red;">Исследование с ID "' .. id .. '" не найдено.</div>'
        else
end
            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 disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
            -- Формирование строки необходимых исследований
local tierColor = tierColors[tech.tier] or "#FFFFFF"
            local prerequisites = ""
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
                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 out = cssLink .. '<div class="research" id="' .. tech.discipline .. '">'
                        if prerequisiteName ~= "" then
out = out .. '<div class="research__images">[[Файл:' .. icon .. '.png|64x64px|центр|link=]]</div>'
                            prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|'.. prerequisiteName .. '}}</li>'
out = out .. '<div class="research__name">' .. tech.name .. '[[Файл:' .. tech.discipline .. '.png|16px|link=]]</div>'
                        end
out = out .. '<div class="research__type">'
                    end
out = out .. '<div>Уровень: <span style="color:' .. tierColor .. ';">' .. tech.tier .. '</span></div>'
                end
out = out .. '<div class="research__technology">' .. disciplineName .. '</div>'
                prerequisites = prerequisites .. '</ul>'
out = out .. '<div>Стоимость: <span style="color:#DA70D6;">' .. tech.cost .. '</span></div>'
            end
out = out .. '</div>'
out = out .. '<div class="research__technologies">'


-- Блок необходимых технологий для открытия исследования
            -- Формирование строки открываемых исследований
if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
local unlocks = ""
out = out .. '<div class="research__technologies-prerequisites"><span style="font-weight:500;">Необходимые технологии:</span>'
if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
    unlocks = '<ul>'
for _, prerequisiteId in ipairs(tech.technologyPrerequisites) do
    for _, recipeId in ipairs(tech.recipeUnlocks) do
local prerequisiteTech = findResearchById(dataCache, prerequisiteId)
        if recipeId and recipeId ~= "" then
            -- Ищем в recipeData объект с id == recipeId
            local newId = recipeId
            for _, rec in ipairs(recipeData) do
                if rec and rec.id == recipeId then
                    newId = rec.result or recipeId
                    break
                end
            end
out = out .. '<span> ' .. prerequisiteTech.name .. '</span>'
            unlocks = unlocks .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
end
                .. newId .. '.png|' .. newId
                .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'
out = out .. '</div>'
                .. newId .. '}}</li>'
end
        end
    end
    unlocks = unlocks .. '</ul>'
end


-- Блок открываемых технологий
            -- Шаблон для отображения блока исследования
out = out .. '<div class="research__technologies-unblocks"><span style="font-weight:500;">Разблокирует:</span>'
            local templateArgs = {
out = out .. '<ul>'
                id = tech.id,
                icon = iconPath,
                name = tech.name,
                discipline = tech.discipline,
                tier = tech.tier,
                tierColor = tierColor,
                disciplineName = disciplineName,
                cost = tech.cost,
                unlocks = unlocks
            }


local recipeUnlocks = customRecipeUnlocks
            -- Добавление prerequisites только если он существует
if #customRecipeUnlocks == 0 then
            if prerequisites ~= "" then
recipeUnlocks = tech.recipeUnlocks
                templateArgs.prerequisites = prerequisites
end
            end


for _, recipe in ipairs(recipeUnlocks) do
            out = out .. frame:expandTemplate({
local machineID = translateBoardIDToMachineID(recipe) or recipe
                title = 'Prototypes/Механика/Исследование',
out = out .. frame:preprocess('<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:' .. machineID .. '.png|' .. machineID .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|' .. machineID .. '}}</li>')
                args = templateArgs
end
            })
 
end
out = out .. '</ul>'
        return mw.getCurrentFrame():preprocess(out)
out = out .. '</div>'
    else
 
        return '<div style="color:red;">Не указан ID исследования.</div>'
out = out .. '</div>'
    end
out = out .. '</div>'
 
return out
end
end


return p
return p