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

мНет описания правки
мНет описания правки
 
(не показаны 32 промежуточные версии этого же участника)
Строка 1: Строка 1:
-- Загрузка данных
local recipeData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local p = {}
local p = {}
local dataCache = nil  -- Кэш для данных плат
local researchDataCache = nil  -- Кэш для данных исследований
-- Функция для загрузки данных плат из JSON-файла
local function loadData()
if not dataCache then
dataCache = mw.text.jsonDecode(mw.title.new("Участник:IanComradeBot/entity_prototypes.json"):getContent())
end
return dataCache
end


-- Функция для загрузки данных исследований из JSON-файла
-- Функция для загрузки данных исследований из JSON-файла
local function loadResearchData()
local function loadResearchData()
if not researchDataCache then
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/research.json"):getContent())
researchDataCache = mw.text.jsonDecode(mw.title.new("User:IanComradeBot/research_prototypes.json"):getContent())
end
return researchDataCache
end
end


-- Кэш для машинных ID
-- Таблица для перевода названий дисциплин
local machineIDCache = {}
local disciplineMapping = {
 
    Arsenal = "Арсенал",
-- Функция для перевода ID плат в ID машин с кэшированием
    Industrial = "Промышленность",
local function translateBoardIDToMachineID(boardID)
    Experimental = "Экспериментальное",
if machineIDCache[boardID] then
    CivilianServices = "Обслуживание персонала"
return machineIDCache[boardID]
}
end
 
-- Загружаем данные плат
local data = loadData()
 
-- Поиск платы по ID
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
local tierColors = {
return nil
    [1] = "#54d554",
end
    [2] = "#ed9000",
 
    [3] = "#d72a2a"
-- Удаление фраз из имени платы
}
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


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


local id = frame.args.id or ""
    -- Получаем ID и иконку из параметров
local icon = frame.args.icon or ""
    local researchId = frame.args[1] or ""
local customRecipeUnlocks = frame.args.customRecipeUnlocks or nil
    local icon = frame.args[2] or ""


-- Загружаем данные исследований из кэша
    if researchId and researchId ~= "" then
local data = loadResearchData()
        local out = ""


local out = cssLink
        -- Поиск исследования по ID
local found = false
        local tech = nil
local disciplineName = ""
        for _, research in ipairs(dataCache) do
            if research and research.id == researchId then
                tech = research
                break
            end
        end


-- Определение дисциплины и отображение исследований
        if not tech then
for discipline, technologies in pairs(data) do
            out = out .. '<div style="color:red;">Исследование с ID "' .. researchId .. '" не найдено.</div>'
for _, tech in ipairs(technologies) do
        else
if tech.id == id then
            local tierColor = tierColors[tech.tier] or "#FFFFFF"
found = true
            local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
disciplineName = ({
            local iconPath = icon ~= "" and icon or (tech.icon and tech.icon.sprite or nil)
Arsenal = "Арсенал",
Industrial = "Промышленность",
Experimental = "Экспериментальное",
CivilianServices = "Обслуживание персонала"
})[discipline]


local tierColor = ({
            -- Формирование строки необходимых исследований
[1] = "#54d554",
            local prerequisites = ""
[2] = "#ed9000",
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
[3] = "#d72a2a"
                prerequisites = '<ul>'
})[tech.tier]
                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


out = out .. '<div class="research" id="' .. discipline .. '">'
                        -- Если название найдено, выводим его
out = out .. '<div class="research__images">[[Файл:' .. icon .. '.png|64x64px|центр|link=]]</div>'
                        if prerequisiteName ~= "" then
out = out .. '<div class="research__name">' .. tech.name .. '[[Файл:' .. discipline .. '.png|16px|link=]]</div>'
                            prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|'.. prerequisiteName .. '}}</li>'
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>'
                end
out = out .. '<div>Стоимость: <span style="color:#DA70D6;">' .. tech.cost .. '</span></div>'
                prerequisites = prerequisites .. '</ul>'
out = out .. '</div>'
            end
out = out .. '<div class="research__unblocks">Разблокирует:'
out = out .. '<ul>'


-- Используем кастомные recipeUnlocks или значения из json файла
            -- Формирование строки открываемых исследований
local recipeUnlocks = customRecipeUnlocks and mw.text.split(customRecipeUnlocks, " ") or tech.recipeUnlocks
local unlocks = ""
if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
    unlocks = '<ul>'
    for _, recipeId in ipairs(tech.recipeUnlocks) do
        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
            unlocks = unlocks .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
                .. newId .. '.png|' .. newId
                .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'
                .. newId .. '}}</li>'
        end
    end
    unlocks = unlocks .. '</ul>'
end


for _, recipe in ipairs(recipeUnlocks) do
            -- Шаблон для отображения блока исследования
local machineID = translateBoardIDToMachineID(recipe) or recipe
            local templateArgs = {
                id = tech.id,
                icon = iconPath,
                name = tech.name,
                discipline = tech.discipline,
                tier = tech.tier,
                tierColor = tierColor,
                disciplineName = disciplineName,  
                cost = tech.cost,
                unlocks = unlocks
            }


out = out .. frame:preprocess('<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:' .. machineID .. '.png|' .. machineID .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|' .. machineID .. '}}</li>')
            -- Добавление prerequisites только если он существует
end
            if prerequisites ~= "" then
                templateArgs.prerequisites = prerequisites
            end


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


return p
return p