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

Материал из Space Station 14 Вики
мНет описания правки
мНет описания правки
 
(не показано 35 промежуточных версий этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}


-- Функция для загрузки данных станков
-----------------------------------------------------------
local function loadLatheData()
-- Загрузка данных
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/lathe.json"):getContent())
-----------------------------------------------------------
end
local latheData    = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
 
local recipeData  = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
-- Функция для загрузки данных рецептов
local researchData = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
local function loadRecipeData()
local materialData = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/lathe/recipes.json"):getContent())
local chemData     = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
end
 
-- Функция для загрузки данных исследований
local function loadResearchData()
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/research.json"):getContent())
end
 
-- Функция для форматирования времени
local function format_seconds_to_short_string(input_seconds)
    local minutes = math.floor(input_seconds / 60)
    local seconds = input_seconds % 60
 
     local minutes_part = minutes > 0 and (minutes .. " мин.") or nil
    local seconds_part = seconds > 0 and (seconds .. " сек.") or nil
 
    if minutes_part and seconds_part then
        return minutes_part .. " " .. seconds_part
    elseif seconds_part then
        return seconds_part
    elseif minutes_part then
        return minutes_part
    else
        return ''
    end
end


-----------------------------------------------------------
-- Функция для сортировки рецептов
-- Функция для сортировки рецептов
-----------------------------------------------------------
local function sortRecipesByPriority(recipes)
local function sortRecipesByPriority(recipes)
     table.sort(recipes, function(a, b)
     table.sort(recipes, function(a, b)
        -- Приоритеты дисциплин
         local priority = { Static = 1, EMAG = 3 }
         local priority = { Static = 1, Unknown = 2, EMAG = 4 }
         local aPriority = priority[a.discipline] or 2
         local aPriority = priority[a.discipline] or 3
         local bPriority = priority[b.discipline] or 2
         local bPriority = priority[b.discipline] or 3


        -- EMAG рецепты всегда в конце
         if a.isEmag ~= b.isEmag then
         if a.isEmag ~= b.isEmag then
             return not a.isEmag
             return not a.isEmag
         end
         end


        -- Если приоритеты совпадают
         if aPriority == bPriority then
         if aPriority == bPriority then
            -- Сравнение по уровню исследования
             if a.tier == b.tier then
             if a.tier == b.tier then
                -- Если уровни совпадают, сортируем по discipline
                 return a.discipline < b.discipline
                 return a.discipline < b.discipline
             end
             end
Строка 58: Строка 30:
         end
         end


        -- Сортируем по приоритету discipline
         return aPriority < bPriority
         return aPriority < bPriority
     end)
     end)
end
end


-----------------------------------------------------------
-- Основная функция модуля
-----------------------------------------------------------
function p.main(frame)
function p.main(frame)
     local latheId = frame.args[1] or ""
     local latheId = frame.args[1] or ""
Строка 68: Строка 42:
         return '<div style="color:red;">Не указан ID станка.</div>'
         return '<div style="color:red;">Не указан ID станка.</div>'
     end
     end
    local latheData = loadLatheData()
    local recipeData = loadRecipeData()
    local researchData = loadResearchData()


     local lathe = nil
     local lathe = nil
Строка 85: Строка 55:
     end
     end


     local output = '<h3>Рецепты станка: ' .. latheId .. '</h3>'
     local materialMapping = {}
    for _, material in ipairs(materialData) do
        if material.id then
            materialMapping[material.id] = material.stackEntity or material.id or material.name
        end
    end


    local chemMapping = {}
    for id, chem in pairs(chemData) do
        chemMapping[id] = chem.name
    end
    local out = ''
     local recipes = {}
     local recipes = {}


Строка 92: Строка 73:
         for _, recipe in ipairs(recipeData) do
         for _, recipe in ipairs(recipeData) do
             if recipe.id == recipeId then
             if recipe.id == recipeId then
                 return recipe.latheRecipe
                 return recipe
             end
             end
         end
         end
Строка 100: Строка 81:
     local function findInResearch(recipeId)
     local function findInResearch(recipeId)
         for _, research in ipairs(researchData) do
         for _, research in ipairs(researchData) do
             if research.technology and research.technology.recipeUnlocks then
             if research and research.recipeUnlocks then
                 for _, unlock in ipairs(research.technology.recipeUnlocks) do
                 for _, unlock in ipairs(research.recipeUnlocks) do
                     if unlock == recipeId then
                     if unlock == recipeId then
                         return {
                         return {
                             name = research.technology.name,
                             name = research.name,
                             tier = research.technology.tier,
                             tier = research.tier,
                             discipline = research.technology.discipline
                             discipline = research.discipline
                         }
                         }
                     end
                     end
Строка 116: Строка 97:


     -- Обработка staticRecipes
     -- Обработка staticRecipes
     if lathe.Lathe.staticRecipes then
     if lathe.Lathe and lathe.Lathe.staticRecipes then
         for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
         for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
             local recipe = getRecipeDetails(recipeId)
             local recipe = getRecipeDetails(recipeId)
             if recipe then
             if recipe and recipe.result then
                 table.insert(recipes, {
                 table.insert(recipes, {
                     result = recipe.result,
                     result = recipe.result,
Строка 127: Строка 108:
                     tier = 0
                     tier = 0
                 })
                 })
            elseif recipe and recipe.resultReagents then
                for reagent, amount in pairs(recipe.resultReagents) do
                    local reagentName = chemMapping[reagent] or reagent
                    table.insert(recipes, {
                        result = reagentName .. "|amount=" .. amount .. "ед.|mode-chem=1",
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = "Static",
                        tier = 0
                    })
                    break
                end
            else
                out = out .. '<div style="color:red;">Ошибка: Рецепт с ID "' .. recipeId .. '" не найден или поля result/resultReagents отсутствуют.</div>'
             end
             end
         end
         end
Строка 132: Строка 127:


     -- Обработка dynamicRecipes
     -- Обработка dynamicRecipes
     if lathe.Lathe.dynamicRecipes then
     if lathe.Lathe and lathe.Lathe.dynamicRecipes then
         for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
         for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
             local recipe = getRecipeDetails(recipeId)
             local recipe = getRecipeDetails(recipeId)
Строка 146: Строка 141:
                         researchName = researchInfo.name
                         researchName = researchInfo.name
                     })
                     })
                 else
                 end
            end
        end
    end
 
    -- Обработка emagStaticRecipes
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagStaticRecipes then
        for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe then
                table.insert(recipes, {
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = "Static",
                    tier = 0,
                    isEmag = true
                })
            end
        end
    end
 
    -- Обработка emagDynamicRecipes
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagDynamicRecipes then
        for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe then
                local researchInfo = findInResearch(recipeId)
                if researchInfo then
                     table.insert(recipes, {
                     table.insert(recipes, {
                         result = recipe.result,
                         result = recipe.result,
                         completetime = recipe.completetime,
                         completetime = recipe.completetime,
                         materials = recipe.materials,
                         materials = recipe.materials,
                         discipline = "Unknown",
                         discipline = researchInfo.discipline,
                         tier = 0
                         tier = researchInfo.tier,
                        researchName = researchInfo.name,
                        isEmag = true
                     })
                     })
                 end
                 end
Строка 159: Строка 184:
     end
     end


-- Обработка emagStaticRecipes
    sortRecipesByPriority(recipes)
if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagStaticRecipes then
 
    for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
    -- Таблица для перевода названий дисциплин
        local recipe = getRecipeDetails(recipeId)
    local disciplineMapping = {
        if recipe then
        Arsenal = "Арсенал",
            table.insert(recipes, {
        Industrial = "Промышленность",
                result = recipe.result,
        Experimental = "Экспериментальное",
                completetime = recipe.completetime,
        CivilianServices = "Обслуживание персонала"
                materials = recipe.materials,
    }
                discipline = "Static",
 
                tier = 0,
    -- Таблица для цветов по уровням
                isEmag = true
    local tierColors = {
            })
        [1] = "#54d554",
        end
        [2] = "#ed9000",
    end
        [3] = "#d72a2a"
end
    }
 
    local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
    local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
 
    for _, recipe in ipairs(recipes) do
        local scaledTime = recipe.completetime * timeMultiplier
        out = out .. '{{Шаблон:Prototypes/Машина/Станок|product=' .. recipe.result
        out = out .. '|complete-time={{#invoke:Code/Формат/Время|main|seconds|' .. scaledTime
        out = out .. '}}|materials='
 
if recipe.materials then
    local materialEntries = {}
    for material, amount in pairs(recipe.materials) do
        local stackEntity = materialMapping[material] or material
        local scaledAmount = (amount * materialUseMultiplier) / 100
        table.insert(materialEntries, string.format('<b>[[File:%s.png|32x32px|link=]] %g {{#invoke:Entity Lookup|getname|%s}}</b>', stackEntity, scaledAmount, stackEntity))
    end
    out = out .. table.concat(materialEntries)
else
    out = out .. 'Нет данных о материалах'
end
 
        -- Информация об исследовании
        if recipe.discipline ~= "Static" then
            local tierColor = tierColors[recipe.tier] or "#FFFFFF"
            local disciplineName = disciplineMapping[recipe.discipline] or "Неизвестная дисциплина"


-- Обработка emagDynamicRecipes
            out = out .. '|info=<div style="font-weight:600;"><span style="margin:8px;">[[File:' .. recipe.discipline .. '.png|16x16px|link=]]</span> [[Руководство по исследованию и разработке|' .. disciplineName
if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagDynamicRecipes then
            out = out .. ']], уровень: <span style="color: ' .. tierColor .. '">' .. recipe.tier .. '</span> </div>'
    for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
        end
        local recipe = getRecipeDetails(recipeId)
        if recipe then
            local researchInfo = findInResearch(recipeId)
            if researchInfo then
                table.insert(recipes, {
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = researchInfo.discipline, -- Discipline из исследования
                    tier = researchInfo.tier, -- Уровень из исследования
                    researchName = researchInfo.name,
                    isEmag = true -- Флаг для пометки EMAG
                })
            else
                table.insert(recipes, {
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = "Unknown", -- Если нет информации об исследовании
                    tier = 0,
                    isEmag = true -- Флаг для пометки EMAG
                })
            end
        end
    end
end
-- Вывод рецептов
for _, recipe in ipairs(recipes) do
    output = output .. '{{Шаблон:Prototypes/Машина/Станок|product=' .. recipe.result
    output = output .. '|complete-time=' .. format_seconds_to_short_string(recipe.completetime)
    output = output .. '|materials='
    for material, amount in pairs(recipe.materials) do
        output = output .. '<li>' .. material .. ': ' .. amount .. '</li>'
    end


    -- Информация об исследовании
        -- Пометка при взломе EMAG
    if recipe.discipline ~= "Static" and recipe.discipline ~= "Unknown" then
        if recipe.isEmag then
        output = output .. '|info=Исследование: ' .. recipe.discipline .. ' - ' .. recipe.researchName
            out = out .. '|mode-emag=1'
        output = output .. ' (Уровень: ' .. recipe.tier .. ')'
        end
    end
   
    -- Пометка EMAG
    if recipe.isEmag then
        output = output .. '<div>Пометка: EMAG</div>'
    end
end


output = output .. '}}'
        -- Пометка для исследуемой технологии
        if recipe.discipline ~= "Static" then
            out = out .. '|mode-research=1'
        end
 
        out = out .. '}}'
    end


     return mw.getCurrentFrame():preprocess(output)
     return mw.getCurrentFrame():preprocess(out)
end
end


return p
return p

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

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

local p = {}

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

-----------------------------------------------------------
-- Функция для сортировки рецептов
-----------------------------------------------------------
local function sortRecipesByPriority(recipes)
    table.sort(recipes, function(a, b)
        local priority = { Static = 1, EMAG = 3 }
        local aPriority = priority[a.discipline] or 2
        local bPriority = priority[b.discipline] or 2

        if a.isEmag ~= b.isEmag then
            return not a.isEmag
        end

        if aPriority == bPriority then
            if a.tier == b.tier then
                return a.discipline < b.discipline
            end
            return a.tier < b.tier
        end

        return aPriority < bPriority
    end)
end

-----------------------------------------------------------
-- Основная функция модуля
-----------------------------------------------------------
function p.main(frame)
    local latheId = frame.args[1] or ""
    if latheId == "" then
        return '<div style="color:red;">Не указан ID станка.</div>'
    end

    local lathe = nil
    for _, data in ipairs(latheData) do
        if data.id == latheId then
            lathe = data
            break
        end
    end

    if not lathe then
        return '<div style="color:red;">Станок с ID "' .. latheId .. '" не найден.</div>'
    end

    local materialMapping = {}
    for _, material in ipairs(materialData) do
        if material.id then
            materialMapping[material.id] = material.stackEntity or material.id or material.name
        end
    end

    local chemMapping = {}
    for id, chem in pairs(chemData) do
        chemMapping[id] = chem.name
    end

    local out = ''
    local recipes = {}

    local function getRecipeDetails(recipeId)
        for _, recipe in ipairs(recipeData) do
            if recipe.id == recipeId then
                return recipe
            end
        end
        return nil
    end

    local function findInResearch(recipeId)
        for _, research in ipairs(researchData) do
            if research and research.recipeUnlocks then
                for _, unlock in ipairs(research.recipeUnlocks) do
                    if unlock == recipeId then
                        return {
                            name = research.name,
                            tier = research.tier,
                            discipline = research.discipline
                        }
                    end
                end
            end
        end
        return nil
    end

    -- Обработка staticRecipes
    if lathe.Lathe and lathe.Lathe.staticRecipes then
        for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe and recipe.result then
                table.insert(recipes, {
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = "Static",
                    tier = 0
                })
            elseif recipe and recipe.resultReagents then
                for reagent, amount in pairs(recipe.resultReagents) do
                    local reagentName = chemMapping[reagent] or reagent
                    table.insert(recipes, {
                        result = reagentName .. "|amount=" .. amount .. "ед.|mode-chem=1",
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = "Static",
                        tier = 0
                    })
                    break 
                end
            else
                out = out .. '<div style="color:red;">Ошибка: Рецепт с ID "' .. recipeId .. '" не найден или поля result/resultReagents отсутствуют.</div>'
            end
        end
    end

    -- Обработка dynamicRecipes
    if lathe.Lathe and lathe.Lathe.dynamicRecipes then
        for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe then
                local researchInfo = findInResearch(recipeId)
                if researchInfo then
                    table.insert(recipes, {
                        result = recipe.result,
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = researchInfo.discipline,
                        tier = researchInfo.tier,
                        researchName = researchInfo.name
                    })
                end
            end
        end
    end

    -- Обработка emagStaticRecipes
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagStaticRecipes then
        for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe then
                table.insert(recipes, {
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = "Static",
                    tier = 0,
                    isEmag = true
                })
            end
        end
    end

    -- Обработка emagDynamicRecipes 
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagDynamicRecipes then
        for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe then
                local researchInfo = findInResearch(recipeId)
                if researchInfo then
                    table.insert(recipes, {
                        result = recipe.result,
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = researchInfo.discipline,
                        tier = researchInfo.tier,
                        researchName = researchInfo.name,
                        isEmag = true
                    })
                end
            end
        end
    end

    sortRecipesByPriority(recipes)

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

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

    local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
    local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1

    for _, recipe in ipairs(recipes) do
        local scaledTime = recipe.completetime * timeMultiplier
        out = out .. '{{Шаблон:Prototypes/Машина/Станок|product=' .. recipe.result
        out = out .. '|complete-time={{#invoke:Code/Формат/Время|main|seconds|' .. scaledTime
        out = out .. '}}|materials='

		if recipe.materials then
		    local materialEntries = {}
		    for material, amount in pairs(recipe.materials) do
		        local stackEntity = materialMapping[material] or material
		        local scaledAmount = (amount * materialUseMultiplier) / 100
		        table.insert(materialEntries, string.format('<b>[[File:%s.png|32x32px|link=]] %g {{#invoke:Entity Lookup|getname|%s}}</b>', stackEntity, scaledAmount, stackEntity))
		    end
		    out = out .. table.concat(materialEntries)
		else
		    out = out .. 'Нет данных о материалах'
		end

        -- Информация об исследовании
        if recipe.discipline ~= "Static" then
            local tierColor = tierColors[recipe.tier] or "#FFFFFF"
            local disciplineName = disciplineMapping[recipe.discipline] or "Неизвестная дисциплина"

            out = out .. '|info=<div style="font-weight:600;"><span style="margin:8px;">[[File:' .. recipe.discipline .. '.png|16x16px|link=]]</span> [[Руководство по исследованию и разработке|' .. disciplineName
            out = out .. ']], уровень: <span style="color: ' .. tierColor .. '">' .. recipe.tier .. '</span> </div>'
        end

        -- Пометка при взломе EMAG
        if recipe.isEmag then
            out = out .. '|mode-emag=1'
        end

        -- Пометка для исследуемой технологии
        if recipe.discipline ~= "Static" then
            out = out .. '|mode-research=1'
        end

        out = out .. '}}'
    end

    return mw.getCurrentFrame():preprocess(out)
end

return p