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

Нет описания правки
мНет описания правки
 
(не показаны 42 промежуточные версии этого же участника)
Строка 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]
local disciplineMapping = {
if not board or not board.name then
    Arsenal = "Арсенал",
return nil -- Если платы нет в данных, возвращаем nil
    Industrial = "Промышленность",
end
    Experimental = "Экспериментальное",
    CivilianServices = "Обслуживание персонала"
}


-- Проверка наличия "(машинная плата)" или "(консольная плата)" в имени
-- Таблица для цветов по уровням
if not board.name:find("%(машинная плата%)") and not board.name:find("%(консольная плата%)") then
local tierColors = {
return nil -- Если в имени нет одной из фраз, возвращаем nil
    [1] = "#54d554",
end
    [2] = "#ed9000",
    [3] = "#d72a2a"
}


-- Удаление "(машинная плата)" и "(консольная плата)" из имени платы
function p.main(frame)
local machineName = board.name:gsub(" %(машинная плата%)", ""):gsub(" %(консольная плата%)", "")
    local dataCache = loadResearchData()


-- Список исключений
    -- Получаем ID и иконку из параметров
local excludeWords = {"Unanchored", "Debug", "Admin"}
    local researchId = frame.args[1] or ""
    local icon = frame.args[2] or ""


-- Поиск машины по новому названию
    if researchId and researchId ~= "" then
for _, entity in pairs(data) do
        local out = ""
if entity.name == machineName then
-- Проверка на наличие исключений в ID
local shouldExclude = false
for _, word in ipairs(excludeWords) do
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
        -- Поиск исследования по ID
end
        local tech = nil
        for _, research in ipairs(dataCache) do
            if research and research.id == researchId then
                tech = research
                break
            end
        end


function p.main(frame)
        if not tech then
-- Подключение CSS файла
            out = out .. '<div style="color:red;">Исследование с ID "' .. researchId .. '" не найдено.</div>'
local cssLink = frame:extensionTag('templatestyles', '', {
        else
src = 'Шаблон:Research/styles.css'
            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 id = frame.args.id or ""
            -- Формирование строки необходимых исследований
local icon = frame.args.icon or ""
            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


-- Загрузка данных из JSON
                        -- Если название найдено, выводим его
local data = mw.text.jsonDecode(mw.title.new("User:IanComradeBot/research prototypes.json"):getContent())
                        if prerequisiteName ~= "" then
                            prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|'.. prerequisiteName .. '}}</li>'
                        end
                    end
                end
                prerequisites = prerequisites .. '</ul>'
            end


local out = cssLink
            -- Формирование строки открываемых исследований
local found = false  -- Флаг для отслеживания наличия элементов
local unlocks = ""
local disciplineName = ""  
if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
 
    unlocks = '<ul>'
-- Определяем дисциплину на основе переданного id
    for _, recipeId in ipairs(tech.recipeUnlocks) do
for discipline, technologies in pairs(data) do
        if recipeId and recipeId ~= "" then  
for _, tech in ipairs(technologies) do
            -- Ищем в recipeData объект с id == recipeId
if tech.id == id then
            local newId = recipeId
found = true
            for _, rec in ipairs(recipeData) do
disciplineName = ({
                if rec and rec.id == recipeId then
Arsenal = "Арсенал",
                    newId = rec.result or recipeId
Industrial = "Промышленность",
                    break
Experimental = "Экспериментальное",
                end
CivilianServices = "Обслуживание персонала"
            end
})[discipline]
 
            unlocks = unlocks .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'  
-- Цвета для номеров уровней
                .. newId .. '.png|' .. newId
local tierColor = ({
                .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'  
[1] = "#54d554",  -- зеленый
                .. newId .. '}}</li>'
[2] = "#ed9000",  -- оранжевый
        end
[3] = "#d72a2a"  -- красный
    end
})[tech.tier]
    unlocks = unlocks .. '</ul>'
 
end
-- Формирование HTML для технологии
out = out .. '<div class="research" id="' .. discipline .. '">'
out = out .. '<div class="research__images">[[Файл:' .. icon .. '.png|64x64px|центр|link=]]</div>' -- Используем переданный icon
out = out .. '<div class="research__name">' .. tech.name .. '[[Файл:' .. discipline .. '.png|16px|link=]]</div>'
out = out .. '<div class="research__type">'
out = out .. '<div>Уровень: <span style="color:' .. tierColor .. ';">' .. tech.tier .. '</span></div>'
out = out .. '<div class="research__technology">' .. disciplineName .. '</div>'
out = out .. '<div>Стоимость: <span style="color:#DA70D6;">' .. tech.cost .. '</span></div>'
out = out .. '</div>'
out = out .. '<div class="research__unblocks">Разблокирует:'
out = out .. '<ul>'


-- Проверка каждого ID в recipeUnlocks
            -- Шаблон для отображения блока исследования
for _, recipe in ipairs(tech.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>Нет доступных технологий.</div>'
    end
end
 
return out
end
end


return p
return p