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

Материал из Space Station 14 Вики
мНет описания правки
мНет описания правки
 
(не показаны 24 промежуточные версии этого же участника)
Строка 1: Строка 1:
-- Загрузка данных
local recipeData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local p = {}
local p = {}
local dataCache = nil  -- Кэш для данных плат
local researchDataCache = nil  -- Кэш для данных исследований
local machineIDCache = {}  -- Кэш для машинных ID
local boardIndex = {}  -- Индекс по ID плат
local machineIndex = {}  -- Индекс по имени машин
-- Функция для загрузки данных плат из JSON-файла и создания индексов
local function loadData()
if not dataCache then
dataCache = mw.text.jsonDecode(mw.title.new("User:IanComradeBot/entity_prototypes.json"):getContent())
-- Создание индекса плат по ID и машин по имени
for id, entity in pairs(dataCache) do
boardIndex[id] = entity
-- Индексируем только машинные или консольные платы
if entity.name and (entity.name:find("%(машинная плата%)") or entity.name:find("%(консольная плата%)")) then
local machineName = entity.name:gsub(" %(машинная плата%)", ""):gsub(" %(консольная плата%)", "")
machineIndex[machineName] = entity.id
end
end
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 плат в ID машин с кэшированием и использованием индексов
-- Таблица для перевода названий дисциплин
local function translateBoardIDToMachineID(boardID)
local disciplineMapping = {
if machineIDCache[boardID] then
    Arsenal = "Арсенал",
return machineIDCache[boardID]
    Industrial = "Промышленность",
end
    Experimental = "Экспериментальное",
 
    CivilianServices = "Обслуживание персонала"
-- Используем индекс для быстрого поиска платы
}
local board = boardIndex[boardID]
if not board then
return nil
end
 
-- Проверка на машинные или консольные платы
local machineName = board.name:gsub(" %(машинная плата%)", ""):gsub(" %(консольная плата%)", "")
local machineID = machineIndex[machineName]


-- Кэшируем результат
-- Таблица для цветов по уровням
machineIDCache[boardID] = machineID or nil
local tierColors = {
return machineID
    [1] = "#54d554",
end
    [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 и иконку из параметров
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 data = loadResearchData()
        local tech = nil
        for _, research in ipairs(dataCache) do
            if research and research.id == researchId then
                tech = research
                break
            end
        end


local out = cssLink
        if not tech then
local found = false
            out = out .. '<div style="color:red;">Исследование с ID "' .. researchId .. '" не найдено.</div>'
local disciplineName = ""
        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)


-- Определение дисциплины и отображение исследований
            -- Формирование строки необходимых исследований
for discipline, technologies in pairs(data) do
            local prerequisites = ""
for _, tech in ipairs(technologies) do
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
if tech.id == id then
                prerequisites = '<ul>'
found = true
                for _, prerequisiteId in ipairs(tech.technologyPrerequisites) do
disciplineName = ({
                    if prerequisiteId and prerequisiteId ~= "" then
Arsenal = "Арсенал",
                        -- Находим название исследования по ID
Industrial = "Промышленность",
                        local prerequisiteName = ""
Experimental = "Экспериментальное",
                        for _, research in ipairs(dataCache) do
CivilianServices = "Обслуживание персонала"
                            if research and research.id == prerequisiteId then
})[discipline]
                                prerequisiteName = research.name
                                break
                            end
                        end


local tierColor = ({
                        -- Если название найдено, выводим его
[1] = "#54d554",
                        if prerequisiteName ~= "" then
[2] = "#ed9000",
                            prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|'.. prerequisiteName .. '}}</li>'
[3] = "#d72a2a"
                        end
})[tech.tier]
                    end
                end
                prerequisites = prerequisites .. '</ul>'
            end


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

Текущая версия от 14:40, 13 февраля 2025

Для документации этого модуля может быть создана страница Модуль:Prototypes/Механика/Исследование/doc

-- Загрузка данных
local recipeData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")

local p = {}

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

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

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

function p.main(frame)
    local dataCache = loadResearchData()

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

    if researchId and researchId ~= "" then
        local out = ""

        -- Поиск исследования по 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
            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 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

                        -- Если название найдено, выводим его
                        if prerequisiteName ~= "" then
                            prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|'.. prerequisiteName .. '}}</li>'
                        end
                    end
                end
                prerequisites = prerequisites .. '</ul>'
            end

            -- Формирование строки открываемых исследований
			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

            -- Шаблон для отображения блока исследования
            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
            }

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

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

return p