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

мНет описания правки
Нет описания правки
 
(не показано 439 промежуточных версий этого же участника)
Строка 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


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 ext = (args["ext"] or "png"):gsub("^%.", "")
local protBlunt = formatPercentage(coefficients and coefficients.Blunt)
    local namespace = args["namespace"] or "Файл"
local protSlash = formatPercentage(coefficients and coefficients.Slash)
    local max = tonumber(args["max"]) or 50
local protPiercing = formatPercentage(coefficients and coefficients.Piercing)
    local include_base = (args["base"] ~= "no")
local protHeat = formatPercentage(coefficients and coefficients.Heat)
local protRadiation = formatPercentage(coefficients and coefficients.Radiation)
local protCaustic = formatPercentage(coefficients and coefficients.Caustic)
local protExplosion = formatPercentage(itemData and itemData.ExplosionResistance)
 
-- Получаем значения sprintModifier, walkModifier, fireProtection, и temperatureProtection
local sprintModifier = itemData and itemData.sprintModifier
local walkModifier = itemData and itemData.walkModifier
local fireProtection = itemData and itemData.FireProtection
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)
if sprintModifier == walkModifier then
speedDescription = "* Понижает скорость передвижения на <span style=\"color:yellow\">'''" .. sprintPercent .. " %'''</span>\n"
else
speedDescription = "* Понижает скорость бега на <span style=\"color:yellow\">'''" .. sprintPercent .. " %'''</span>\n"
speedDescription = speedDescription .. "* Понижает скорость ходьбы на <span style=\"color:yellow\">'''" .. walkPercent .. " %'''</span>\n"
end
end


-- Формируем сообщение для огневой защиты, если значение присутствует
    local found = {}
local fireProtectionDescription = ""
if fireProtection then
local fireProtectionPercent = round((1 - fireProtection) * 100)
fireProtectionDescription = "* Имеет огневую защиту в <span style=\"color:OrangeRed\">'''" .. fireProtectionPercent .. " %'''</span>\n"
end


-- Формируем сообщение для сопротивления к критическим температурам, если значение присутствует
    if include_base then
local temperatureProtectionDescription = ""
        local t = mw.title.new("Файл:" .. name .. "." .. ext)
if temperatureProtection then
        if t and t.exists then
temperatureProtectionDescription = "* Имеет значительное сопротивление к критическим температурам\n"
            table.insert(found, "")
end
        end
    end


-- Описание и местоположение
    for i = 1, max do
local description = (frame.args.description or "") .. '\n' .. speedDescription .. fireProtectionDescription .. temperatureProtectionDescription -- Описание
        local t = mw.title.new("Файл:" .. name .. "-" .. i .. "." .. ext)
local location = frame.args.location or "" -- Местонахождение
        if t and t.exists then
local created = frame.args.created or "" -- Создание
            table.insert(found, "-" .. i)
        end
    end


local anchorName = frame.args.anchorName or "" -- Название якоря
    if #found == 0 then
local backgroundColor = frame.args.backgroundColor or "" -- Цвет фона первой ячейки
        return ""
local class = frame.args.class or "" -- Класс
    end


-- Формирование строк для ячеек таблицы
    local before = "[[" .. namespace .. ":" .. name
local out = ""
    local after = "." .. ext .. "|" .. attributes .. "]]"
out = out .. '!class="' .. class .. '" style="background-color: ' .. backgroundColor .. ';"|' .. frame:preprocess('{{Anchor|' .. anchorName .. '}}')
out = out .. frame:preprocess('{{#invoke:Entity Lookup|createimagetooltip|File:' .. id .. '|' .. id .. '|Мета=64x64px}}')
out = out .. '<br>' .. frame:preprocess('{{#invoke:Entity Lookup|getname|' .. id .. '}}') .. '\n'
out = out .. '|class="' .. class .. '" style="font-weight:bold;color: crimson;"|' .. protBlunt .. '\n'
out = out .. '|class="' .. class .. '" style="font-weight:bold;color: indianred;"|' .. protSlash .. '\n'
out = out .. '|class="' .. class .. '" style="font-weight:bold;color: darksalmon;"|' .. protPiercing .. '\n'
out = out .. '|class="' .. class .. '" style="font-weight:bold;color: orange;"|' .. protHeat .. '\n'
out = out .. '|class="' .. class .. '" style="font-weight:bold;color: plum;"|' .. protCaustic .. '\n'
out = out .. '|class="' .. class .. '" style="font-weight:bold;color: limegreen;"|' .. protRadiation .. '\n'
out = out .. '|class="' .. class .. '" style="font-weight:bold;color: tan;"|' .. protExplosion .. '\n'
out = out .. '|class="' .. class .. '" style=""|\n' .. description .. '\n'
-- Местоположение
out = out .. '|class="' .. class .. '" style=""|\n'
if 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 parts = {}
if created ~= "" then
    table.insert(parts, "<choose before=\"" .. before .. "\" after=\"" .. after .. "\">")
out = out .. frame:preprocess('{{SlideMenu|overlay|color=#e1f6ff|border-color=#4c4c61|title=Создаётся [[File:hammer.svg.192dpi.png|24x24px]]|content=Создаётся в панели строительства<hr>\n' .. created .. '}}\n')
    for _, suf in ipairs(found) do
elseif location == "" then
        table.insert(parts, "<option>" .. suf .. "</option>")
out = out .. frame:preprocess('{{FrameText|color=#82d1c4|content=Нет гарантированных мест спавна}}\n')
    end
end
    table.insert(parts, "</choose>")
out = out .. '|-\n'


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


return p
return p