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

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


-- Функция для перевода ID плат в ID машин
-- Функция для загрузки данных исследований из JSON-файла
local function translateBoardIDToMachineID(boardID)
local function loadResearchData()
-- Загрузка данных из JSON
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/research.json"):getContent())
local data = mw.text.jsonDecode(mw.title.new("Участник:IanComradeBot/entity_prototypes.json"):getContent())
end
 
-- Поиск платы по ID и извлечение её названия
local board = data[boardID]
if not board or not board.name then
return nil -- Если платы нет в данных, возвращаем nil
end
 
-- Проверка наличия "(машинная плата)" или "(консольная плата)" в имени
if not board.name:find("%(машинная плата%)") and not board.name:find("%(консольная плата%)") then
return nil -- Если в имени нет одной из фраз, возвращаем nil
end
 
-- Удаление "(машинная плата)" и "(консольная плата)" из имени платы
local machineName = board.name:gsub(" %(машинная плата%)", ""):gsub(" %(консольная плата%)", "")
 
-- Список исключений
local excludeWords = {"Unanchored", "Debug", "Admin", "Enabled"}


-- Поиск машины по новому названию
-- Таблица для перевода названий дисциплин
for _, entity in pairs(data) do
local disciplineMapping = {
if entity.name == machineName then
    Arsenal = "Арсенал",
-- Проверка на наличие исключений в ID
    Industrial = "Промышленность",
local shouldExclude = false
    Experimental = "Экспериментальное",
for _, word in ipairs(excludeWords) do
    CivilianServices = "Обслуживание персонала"
if entity.id:find(word) then
}
shouldExclude = true
break
end
end
if not shouldExclude then
return entity.id -- Возвращаем ID машины
end
end
end


return nil -- Если машина не найдена, возвращаем nil
-- Таблица для цветов по уровням
end
local tierColors = {
    [1] = "#54d554",
    [2] = "#ed9000",
    [3] = "#d72a2a"
}


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 исследования
    -- Получаем 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 ""


-- Загрузка данных из JSON
    if researchId and researchId ~= "" then
local data = mw.text.jsonDecode(mw.title.new("User:IanComradeBot/research_prototypes.json"):getContent())
        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


-- Определяем дисциплину на основе переданного id
        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 = ({
            local prerequisites = ""
[1] = "#54d554"-- зеленый
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
[2] = "#ed9000", -- оранжевый
                prerequisites = '<ul>'
[3] = "#d72a2a"  -- красный
                for _, prerequisiteId in ipairs(tech.technologyPrerequisites) do
})[tech.tier]
                    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


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


-- Используем пользовательские recipeUnlocks, если они указаны, иначе используем значения из json файла
            -- Формирование строки открываемых исследований
local recipeUnlocks
local unlocks = ""
if customRecipeUnlocks then
if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
recipeUnlocks = mw.text.split(customRecipeUnlocks, " ") -- Разбиваем по пробелам
    unlocks = '<ul>'
else
    for _, recipeId in ipairs(tech.recipeUnlocks) do
recipeUnlocks = tech.recipeUnlocks
        if recipeId and recipeId ~= "" then
end
            -- Ищем в 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


-- Проверка каждого ID в recipeUnlocks
            -- Шаблон для отображения блока исследования
for _, recipe in ipairs(recipeUnlocks) do
            local templateArgs = {
local machineID = translateBoardIDToMachineID(recipe) or recipe  -- Переводим только платы, остальные оставляем как есть
                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