Модуль:ArmorStats: различия между версиями

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


function p.templateCells(frame)
-- Функция для загрузки данных плат из JSON-файла
    local color = frame.args.color or ""  -- Цвет фона
local function loadData()
    local anchorName = frame.args.anchorName or ""  -- Название якоря
return mw.text.jsonDecode(mw.title.new("Участник:IanComradeBot/prototypes/armor.json"):getContent())
    local image = frame.args.image or ""  -- Путь к изображению предмета
end
    local itemId = frame.args.itemId or ""  -- ID предмета
   
    local protection1 = frame.args.protection1 or "-" -- Ударный
    local protection2 = frame.args.protection2 or "-" -- Режущий
    local protection3 = frame.args.protection3 or "-" -- Колющий
    local protection4 = frame.args.protection4 or "-" -- Высокотемпературный
    local protection5 = frame.args.protection5 or "-" -- Кислотный
    local protection6 = frame.args.protection6 or "-" -- Радиационный
    local protection7 = frame.args.protection7 or "-" -- Взрывной
   
    local description = frame.args.description or "" -- Описание
    local location = frame.args.location or "" -- Местонахождение


    -- Вызов шаблона Anchor
-- Функция для поиска данных по ID
    local anchor = frame:expandTemplate{ title = 'Anchor', args = { anchorName } }
local function findDataById(dataCache, id)
for _, item in ipairs(dataCache) do
if item.id == id then
return item
end
end
return nil
end


    -- Вызов функции из модуля Entity Lookup для создания image tooltip
-- Функция для точного округления до ближайшего целого числа
    local imageTooltip = frame:expandTemplate{
local function round(num)
        title = 'Entity Lookup', args = { 'createimagetooltip', 'File:' .. image, itemId, 'Мета=64x64px' }
return math.floor(num + 0.5)
    }
end


    -- Вызов функции из модуля Entity Lookup для получения имени элемента
-- Функция для преобразования значения в проценты
    local itemName = frame:expandTemplate{
local function formatPercentage(value)
        title = 'Entity Lookup', args = { 'getname', itemId }
return value and round((1 - value) * 100) .. "%" or "-"
    }
end


    -- Формирование строк для ячеек таблицы
-- Функция для создания строк для таблицы по типу защиты
    local out = ""
local function createProtectionRow(class, color, value)
    out = out .. '!style="background-color: ' .. color .. ';"|' .. anchor
return '|class="' .. class .. '" style="font-weight:bold;color: ' .. color .. ';"|' .. value .. '\n'
    out = out .. imageTooltip
end
    out = out .. '<br>' .. itemName .. '\n'
    out = out .. '|style="font-weight:500;color: crimson"|' .. protection1 .. '\n'
    out = out .. '|style="font-weight:500;color: indianred"|' .. protection2 .. '\n'
    out = out .. '|style="font-weight:500;color: darksalmon"|' .. protection3 .. '\n'
    out = out .. '|style="font-weight:500;color: orange"|' .. protection4 .. '\n'
    out = out .. '|style="font-weight:500;color: plum"|' .. protection5 .. '\n'
    out = out .. '|style="font-weight:500;color: limegreen"|' .. protection6 .. '\n'
    out = out .. '|style="font-weight:500;color: tan"|' .. protection7 .. '\n'
    out = out .. '|\n' .. description .. '\n\n|\n' .. location .. '\n|-\n'


    return out
function p.main(frame)
local dataCache = loadData()
local id = frame.args.id or "" -- ID предмета
local itemData = findDataById(dataCache, id)
 
-- Получаем защитные значения из armor, если они присутствуют
local armor = itemData and itemData.Armor and itemData.Armor.modifiers and itemData.Armor.modifiers.coefficients
local protBlunt = formatPercentage(armor and armor.Blunt)
local protSlash = formatPercentage(armor and armor.Slash)
local protPiercing = formatPercentage(armor and armor.Piercing)
local protHeat = formatPercentage(armor and armor.Heat)
local protRadiation = formatPercentage(armor and armor.Radiation)
local protCaustic = formatPercentage(armor and armor.Caustic)
local protExplosion = formatPercentage(itemData and itemData.ExplosionResistance and itemData.ExplosionResistance.damageCoefficient)
 
-- Получаем значения sprintModifier, walkModifier, fireProtection
local sprintModifier = itemData and itemData.ClothingSpeedModifier and itemData.ClothingSpeedModifier.sprintModifier
local walkModifier = itemData and itemData.ClothingSpeedModifier and itemData.ClothingSpeedModifier.walkModifier
local fireProtection = itemData and itemData.FireProtection and itemData.FireProtection.reduction
local speedDescription = ""
 
-- Формируем сообщение в зависимости от значений sprintModifier и walkModifier
if sprintModifier and walkModifier then
    if sprintModifier == 1 and walkModifier == 1 then
        speedDescription = ""
    elseif sprintModifier == walkModifier then
        local percent = round(math.abs(sprintModifier - 1) * 100)
        local action = sprintModifier > 1 and "Повышает" or "Понижает"
        speedDescription = string.format("* %s скорость передвижения на <span style=\"color:yellow\">'''%d %%'''</span>\n", action, percent)
    else
        speedDescription = ""
        for _, modifier in ipairs({{sprintModifier, "бега"}, {walkModifier, "ходьбы"}}) do
            local value, actionType = modifier[1], modifier[2]
            if value ~= 1 then
                local percent = round(math.abs(value - 1) * 100)
                local action = value > 1 and "Повышает" or "Понижает"
                speedDescription = speedDescription .. string.format("* %s скорость %s на <span style=\"color:yellow\">'''%d %%'''</span>\n", action, actionType, percent)
            end
        end
    end
end
 
-- Формируем сообщение для огневой защиты, если значение присутствует
local fireProtectionDescription = fireProtection and
"* Имеет огневую защиту в <span style=\"color:OrangeRed\">'''" .. round((1 - fireProtection) * 100) .. " %'''</span>\n" or ""
 
-- Описание и местоположение
local description = (frame.args.description or "") .. '\n' .. speedDescription .. fireProtectionDescription -- Описание
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'
 
-- Используем функцию для формирования строк защиты
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'
out = out .. '|class="' .. class .. '" style=""|\n'
 
 
-- Проверка класса на "spacesuit-helmet"
if class == "spacesuit-helmet" then
out = out .. frame:preprocess("{{FrameText|color = #bcceff|border-color = #4c4c61|content = Находится в скафандре}}")
-- Местоположение
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
 
-- Создаётся
if created ~= "" then
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'
 
return out
end
end


return p
return p