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

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


-- Функция для загрузки данных исследований из 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
end


-- Функция для перевода ID плат в ID машин без кэширования
-- Таблица для перевода названий дисциплин
local function translateBoardIDToMachineID(boardID)
local disciplineMapping = {
-- Загруза данных плат
    Arsenal = "Арсенал",
local data = loadData()
    Industrial = "Промышленность",
 
    Experimental = "Экспериментальное",
-- Поиск платы по ID
    CivilianServices = "Обслуживание персонала"
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
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 customRecipeUnlocksIndexes = {}
        local out = ""
local i = 1
while true do
local customIndex = frame.args["customRecipeUnlocksIndex" .. i]
if not customIndex then
break
end
table.insert(customRecipeUnlocksIndexes, {index = i, recipe = customIndex})
i = i + 1  -- Увеличиваем индекс
end


        -- Поиск исследования по 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
local data = loadResearchData()
            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 out = cssLink
            -- Формирование строки необходимых исследований
local found = false
            local prerequisites = ""
local disciplineName = ""
            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


-- Определение дисциплины и отображение исследований
                        -- Если название найдено, выводим его
for discipline, technologies in pairs(data) do
                        if prerequisiteName ~= "" then
for _, tech in ipairs(technologies) do
                            prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|'.. prerequisiteName .. '}}</li>'
if tech.id == id then
                        end
found = true
                    end
disciplineName = ({
                end
Arsenal = "Арсенал",
                prerequisites = prerequisites .. '</ul>'
Industrial = "Промышленность",
            end
Experimental = "Экспериментальное",
CivilianServices = "Обслуживание персонала"
})[discipline]


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


-- Замена рецептов по индексам
            -- Шаблон для отображения блока исследования
for _, customIndex in ipairs(customRecipeUnlocksIndexes) do
            local templateArgs = {
if recipeUnlocks[customIndex.index] then
                id = tech.id,
recipeUnlocks[customIndex.index] = customIndex.recipe
                icon = iconPath,
end
                name = tech.name,
end
                discipline = tech.discipline,
                tier = tech.tier,
                tierColor = tierColor,
                disciplineName = disciplineName,
                cost = tech.cost,
                unlocks = unlocks
            }


for _, recipe in ipairs(recipeUnlocks) do
            -- Добавление prerequisites только если он существует
local machineID = translateBoardIDToMachineID(recipe) or recipe
            if prerequisites ~= "" then
                templateArgs.prerequisites = prerequisites
            end


out = out .. frame:preprocess('<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:' .. machineID .. '.png|' .. machineID .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|' .. machineID .. '}}</li>')
            out = out .. frame:expandTemplate({
end
                title = 'Prototypes/Механика/Исследование',
 
                args = templateArgs
out = out .. '</ul>'
            })
out = out .. '</div>'
out = out .. '</div>'
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