Модуль:Песочница/Pok: различия между версиями

Материал из Space Station 14 Вики
мНет описания правки
Нет описания правки
 
(не показаны 433 промежуточные версии этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}
 
local getArgs = require('Module:Arguments').getArgs
-- Функция для загрузки данных плат из JSON-файла
local function loadData()
return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/armor_prototypes.json"):getContent())
end
 
-- Функция для поиска данных по ID
local function findDataById(dataCache, id)
for _, item in ipairs(dataCache) do
if item.id == id then
return item
end
end
return nil
end
 
-- Функция для точного округления до ближайшего целого числа
local function round(num)
return math.floor(num + 0.5)
end
 
-- Функция для преобразования значения в проценты
local function formatPercentage(value)
return value and round((1 - value) * 100) .. "%" or "-"
end
 
-- Функция для создания строк для таблицы по типу защиты
local function createProtectionRow(class, color, value)
return '|class="' .. class .. '" style="font-weight:bold;color: ' .. color .. ';"|' .. value .. '\n'
end


function p.main(frame)
function p.main(frame)
local dataCache = loadData()
    local args = getArgs(frame, { removeBlanks = false })
local id = frame.args.id or "" -- ID предмета
    local name = args[1] or ""
local itemData = findDataById(dataCache, id)
    local attributes = args[2] or ""
 
    if name == "" then
-- Получаем защитные значения из coefficients, если они присутствуют
        return "<span class=\"error\">Ошибка: не указано имя файла.</span>"
local coefficients = itemData and itemData.coefficients
    end
local protBlunt = formatPercentage(coefficients and coefficients.Blunt)
    local ext = (args["ext"] or "png"):gsub("^%.", "")  
local protSlash = formatPercentage(coefficients and coefficients.Slash)
    local namespace = args["namespace"] or "Файл"
local protPiercing = formatPercentage(coefficients and coefficients.Piercing)
    local max = tonumber(args["max"]) or 50
local protHeat = formatPercentage(coefficients and coefficients.Heat)
    local include_base = (args["base"] ~= "no")
local protRadiation = formatPercentage(coefficients and coefficients.Radiation)
local protCaustic = formatPercentage(coefficients and coefficients.Caustic)
local protExplosion = formatPercentage(itemData and itemData.ExplosionResistance and itemData.ExplosionResistance.damageCoefficient)
 
-- Получаем значения sprintModifier, walkModifier, fireProtection, и temperatureProtection
local sprintModifier = itemData and itemData.sprintModifier
local walkModifier = itemData and itemData.walkModifier
local fireProtection = itemData and itemData.FireProtection and itemData.FireProtection.reduction
local temperatureProtection = itemData and itemData.TemperatureProtection
local speedDescription = ""
 
-- Формируем сообщение в зависимости от значений sprintModifier и walkModifier
if sprintModifier and walkModifier then
local sprintPercent = round((1 - sprintModifier) * 100)
local walkPercent = round((1 - walkModifier) * 100)
 
speedDescription = "* Понижает скорость " .. (sprintModifier == walkModifier and "передвижения" or "бега и ходьбы") ..
  " на <span style=\"color:yellow\">'''" .. sprintPercent .. " %'''</span>\n"
if sprintModifier ~= walkModifier then
speedDescription = speedDescription .. "* Понижает скорость ходьбы на <span style=\"color:yellow\">'''" .. walkPercent .. " %'''</span>\n"
end
end
 
-- Формируем сообщение для огневой защиты, если значение присутствует
local fireProtectionDescription = fireProtection and
"* Имеет огневую защиту в <span style=\"color:OrangeRed\">'''" .. round((1 - fireProtection) * 100) .. " %'''</span>\n" or ""
 
-- Формируем сообщение для сопротивления к критическим температурам, если значение присутствует
local temperatureProtectionDescription = temperatureProtection and
"* Имеет значительное сопротивление к критическим температурам\n" or ""
 
-- Описание и местоположение
local description = (frame.args.description or "") .. '\n' .. speedDescription .. fireProtectionDescription .. temperatureProtectionDescription -- Описание
local location = frame.args.location or "" -- Местонахождение
local created = frame.args.created or "" -- Создание
 
local anchorName = frame.args.anchorName or "" -- Название якоря
local backgroundColor = frame.args.backgroundColor or "" -- Цвет фона первой ячейки
local class = frame.args.class or "" -- Класс
 
-- Формирование строк для ячеек таблицы
local out = ''
out = out .. '!class="' .. class .. '" style="background-color: ' .. backgroundColor .. ';"|' .. frame:preprocess('{{Anchor|' .. anchorName .. '}}')  
out = out .. frame:preprocess('{{#invoke:Entity Lookup|createimagetooltip|File:' .. id .. '.png|' .. id .. '|Мета=64x64px,link=}}')
out = out .. '<br>' .. frame:preprocess('{{#invoke:Entity Lookup|getname|' .. id .. '}}') .. '\n'


-- Используем функцию для формирования строк защиты
    local found = {}
out = out .. createProtectionRow(class, "crimson", protBlunt)
out = out .. createProtectionRow(class, "indianred", protSlash)
out = out .. createProtectionRow(class, "darksalmon", protPiercing)
out = out .. createProtectionRow(class, "orange", protHeat)
out = out .. createProtectionRow(class, "plum", protCaustic)
out = out .. createProtectionRow(class, "limegreen", protRadiation)
out = out .. createProtectionRow(class, "tan", protExplosion)


out = out .. '|class="' .. class .. '" style=""|\n' .. description .. '\n'
    if include_base then
out = out .. '|class="' .. class .. '" style=""|\n'
        local t = mw.title.new("Файл:" .. name .. "." .. ext)
        if t and t.exists then
            table.insert(found, "")
        end
    end


    for i = 1, max do
        local t = mw.title.new("Файл:" .. name .. "-" .. i .. "." .. ext)
        if t and t.exists then
            table.insert(found, "-" .. i)
        end
    end


-- Проверка класса на "spacesuit-helmet"
    if #found == 0 then
if class == "spacesuit-helmet" then
        return ""
out = out .. frame:preprocess("{{FrameText|color = #bcceff|border-color = #4c4c61|content = Находится в скафандре}}")
    end
-- Местоположение
elseif location ~= "" then
out = out .. frame:preprocess('{{SlideMenu|overlay|color=#e1f6ff|title=Список [[File:Examine.svg.192dpi.png|24x24px]]|content=<p></p>\n' .. location .. '}}\n')
end


-- Создаётся
    local before = "[[" .. namespace .. ":" .. name
if created ~= "" then
    local after = "." .. ext .. "|" .. attributes .. "]]"
out = out .. frame:preprocess('{{SlideMenu|overlay|color=#e1f6ff|border-color=#4c4c61|title=Создаётся [[File:hammer.svg.192dpi.png|24x24px]]|content=Создаётся в панели строительства<hr>\n' .. created .. '}}\n')
elseif location == "" and class ~= "spacesuit-helmet" then
out = out .. frame:preprocess('{{FrameText|color=#82d1c4|content=Нет гарантированных мест спавна}}\n')
end


out = out .. '|-\n'
    local parts = {}
    table.insert(parts, "<choose before=\"" .. before .. "\" after=\"" .. after .. "\">")
    for _, suf in ipairs(found) do
        table.insert(parts, "<option>" .. suf .. "</option>")
    end
    table.insert(parts, "</choose>")


return out
    return frame:preprocess(table.concat(parts, "\n"))
end
end


return p
return p

Текущая версия от 02:52, 17 марта 2026

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

local p = {}
local getArgs = require('Module:Arguments').getArgs

function p.main(frame)
    local args = getArgs(frame, { removeBlanks = false })
    local name = args[1] or ""
    local attributes = args[2] or ""
    if name == "" then
        return "<span class=\"error\">Ошибка: не указано имя файла.</span>"
    end
    local ext = (args["ext"] or "png"):gsub("^%.", "") 
    local namespace = args["namespace"] or "Файл"
    local max = tonumber(args["max"]) or 50
    local include_base = (args["base"] ~= "no")

    local found = {}

    if include_base then
        local t = mw.title.new("Файл:" .. name .. "." .. ext)
        if t and t.exists then
            table.insert(found, "")
        end
    end

    for i = 1, max do
        local t = mw.title.new("Файл:" .. name .. "-" .. i .. "." .. ext)
        if t and t.exists then
            table.insert(found, "-" .. i)
        end
    end

    if #found == 0 then
        return ""
    end

    local before = "[[" .. namespace .. ":" .. name
    local after = "." .. ext .. "|" .. attributes .. "]]"

    local parts = {}
    table.insert(parts, "<choose before=\"" .. before .. "\" after=\"" .. after .. "\">")
    for _, suf in ipairs(found) do
        table.insert(parts, "<option>" .. suf .. "</option>")
    end
    table.insert(parts, "</choose>")

    return frame:preprocess(table.concat(parts, "\n"))
end

return p