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

Материал из Space Station 14 Вики
Нет описания правки
мНет описания правки
(не показаны 33 промежуточные версии этого же участника)
Строка 3: Строка 3:
-- Функция для загрузки данных станков
-- Функция для загрузки данных станков
local function loadLatheData()
local function loadLatheData()
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/lathe.json"):getContent())
return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/lathe.json"):getContent())
end
end


-- Функция для загрузки данных рецептов
-- Функция для загрузки данных рецептов
local function loadRecipeData()
local function loadRecipeData()
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/lathe/recipes.json"):getContent())
return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/lathe/recipes.json"):getContent())
end
end


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


-- Функция для форматирования времени
-- Функция для форматирования времени
local function format_seconds_to_short_string(input_seconds)
local function format_seconds_to_short_string(input_seconds)
    local minutes = math.floor(input_seconds / 60)
local minutes = math.floor(input_seconds / 60)
    local seconds = input_seconds % 60
local seconds = input_seconds % 60


    local minutes_part = minutes > 0 and (minutes .. " мин.") or nil
local minutes_part = minutes > 0 and (minutes .. " мин.") or nil
    local seconds_part = seconds > 0 and (seconds .. " сек.") or nil
local seconds_part = seconds > 0 and (seconds .. " сек.") or nil


    if minutes_part and seconds_part then
if minutes_part and seconds_part then
        return minutes_part .. " " .. seconds_part
return minutes_part .. " " .. seconds_part
    elseif seconds_part then
elseif seconds_part then
        return seconds_part
return seconds_part
    elseif minutes_part then
elseif minutes_part then
        return minutes_part
return minutes_part
    else
else
        return ''
return '0 сек.'
    end
end
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
            -- Сравнение по уровню исследования
return a.discipline < b.discipline
            if a.tier == b.tier then
end
                -- Если уровни совпадают, сортируем по discipline
return a.tier < b.tier
                return a.discipline < b.discipline
end
            end
            return a.tier < b.tier
        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 ""
-- Подключение CSS
    if latheId == "" then
local cssLink = frame:extensionTag('templatestyles', '', {
        return '<div style="color:red;">Не указан ID станка.</div>'
src = 'Шаблон:Prototypes/Машина/Станок/styles.css'
    end
})
 
local latheId = frame.args[1] or ""
if latheId == "" then
return '<div style="color:red;">Не указан ID станка.</div>'
end


    local latheData = loadLatheData()
local latheData = loadLatheData()
    local recipeData = loadRecipeData()
local recipeData = loadRecipeData()
    local researchData = loadResearchData()
local researchData = loadResearchData()
local materialData = loadMaterialData()
local chemData = loadChemData()


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


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


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


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


    local function getRecipeDetails(recipeId)
local out = cssLink
        for _, recipe in ipairs(recipeData) do
local recipes = {}
            if recipe.id == recipeId then
                return recipe.latheRecipe
            end
        end
        return nil
    end


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


    -- Обработка staticRecipes
local function findInResearch(recipeId)
    if lathe.Lathe.staticRecipes then
for _, research in ipairs(researchData) do
        for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
if research.technology and research.technology.recipeUnlocks then
            local recipe = getRecipeDetails(recipeId)
for _, unlock in ipairs(research.technology.recipeUnlocks) do
            if recipe then
if unlock == recipeId then
                table.insert(recipes, {
return {
                    result = recipe.result,
name = research.technology.name,
                    completetime = recipe.completetime,
tier = research.technology.tier,
                    materials = recipe.materials,
discipline = research.technology.discipline
                    discipline = "Static",
}
                    tier = 0
end
                })
end
            end
end
        end
end
    end
return nil
end


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


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


    output = output .. '</ul>'
return mw.getCurrentFrame():preprocess(out)
    return output
end
end


return p
return p

Версия от 14:10, 29 января 2025

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

local p = {}

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

-- Функция для загрузки данных рецептов
local function loadRecipeData()
	return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/lathe/recipes.json"):getContent())
end

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

-- Функция для загрузки данных материалов
local function loadMaterialData()
	return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/materials.json"):getContent())
end

-- Функция для загрузки данных химических веществ
local function loadChemData()
	return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/chem prototypes.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 '0 сек.'
	end
end

-- Функция для сортировки рецептов
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)
	-- Подключение CSS
	local cssLink = frame:extensionTag('templatestyles', '', {
		src = 'Шаблон:Prototypes/Машина/Станок/styles.css'
	})

	local latheId = frame.args[1] or ""
	if latheId == "" then
		return '<div style="color:red;">Не указан ID станка.</div>'
	end

	local latheData = loadLatheData()
	local recipeData = loadRecipeData()
	local researchData = loadResearchData()
	local materialData = loadMaterialData()
	local chemData = loadChemData()

	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
		materialMapping[material.material.id] = material.material.stackEntity
	end

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

	local out = cssLink
	local recipes = {}

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

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

	-- Обработка staticRecipes
	if 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
					if type(reagent) == "string" and reagent ~= "category" then
						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
				end
			else
				out = out .. '<div style="color:red;">Ошибка: Рецепт с ID "' .. recipeId .. '" не найден или поля result/resultReagents отсутствуют.</div>'
			end
		end
	end

	-- Обработка dynamicRecipes
	if 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.materialUseMultiplier or 1
	local timeMultiplier = lathe.Lathe.timeMultiplier or 1

	for _, recipe in ipairs(recipes) do
		local scaledTime = format_seconds_to_short_string(recipe.completetime * timeMultiplier)
		out = out .. '{{Шаблон:Prototypes/Машина/Станок|product=' .. recipe.result
		out = out .. '|complete-time=' .. scaledTime
		out = out .. '|materials='

		if next(recipe.materials) then
			for material, amount in pairs(recipe.materials) do
				local stackEntity = materialMapping[material] or material
				local scaledAmount = (amount * materialUseMultiplier) / 100
				out = out .. '<b>[[File:' .. stackEntity .. '.png|32x32px|link=]] ' .. scaledAmount .. ' {{#invoke:Entity Lookup|getname|' .. stackEntity .. '}}</b>'
			end
		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