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

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


-- Функция для изменения яркости цвета (уменьшение на 20%)
-- Функция для загрузки данных плат из JSON-файла
local function darkenColor(color)
local function loadData()
    -- Уменьшаем каждую компоненту RGB на 20%
return mw.text.jsonDecode(mw.title.new("Участник:IanComradeBot/prototypes/armor.json"):getContent())
    local r = math.floor(tonumber(color:sub(2, 3), 16) * 0.8)
    local g = math.floor(tonumber(color:sub(4, 5), 16) * 0.8)
    local b = math.floor(tonumber(color:sub(6, 7), 16) * 0.8)
    -- Собираем новый цвет
    return string.format("#%02x%02x%02x", r, g, b)
end
end


function p.templateCells(frame)
-- Функция для поиска данных по ID
    local anchorName = frame.args.anchorName or ""  -- Название якоря
local function findDataById(dataCache, id)
    local image = frame.args.image or ""  -- Путь к изображению предмета
for _, item in ipairs(dataCache) do
    local itemId = frame.args.itemId or ""  -- ID предмета
if item.id == id then
    local color = frame.args.color or ""  -- Цвет фона первой ячейки
return item
    local backgroundColor = frame.args.backgroundColor or "" -- Цвет фона для всех ячеек, кроме первой
end
    local class = frame.args.class or "" -- Класс
end
return nil
end


    local protBlunt = frame.args.protBlunt or "-" -- Ударный
-- Функция для точного округления до ближайшего целого числа
    local protSlash = frame.args.protSlash or "-" -- Режущий
local function round(num)
    local protPiercing = frame.args.protPiercing or "-" -- Колющий
return math.floor(num + 0.5)
    local protHeat = frame.args.protHeat or "-" -- Высокотемпературный
end
    local protRadiation = frame.args.protRadiation or "-" -- Кислотный
    local protCaustic = frame.args.protCaustic or "-" -- Радиационный
    local protExplosion = frame.args.protExplosion or "-" -- Взрывной


    local description = frame.args.description or "" -- Описание
-- Функция для преобразования значения в проценты
    local location = frame.args.location or "" -- Местонахождение
local function formatPercentage(value)
return value and round((1 - value) * 100) .. "%" or "-"
end


    -- Вызов функции из модуля Entity Lookup для создания image tooltip
-- Функция для создания строк для таблицы по типу защиты
    local imageTooltip = frame:preprocess('{{#invoke:Entity Lookup|createimagetooltip|File:' .. image .. '|' .. itemId .. '|Мета=64x64px}}')
local function createProtectionRow(class, color, value)
 
return '|class="' .. class .. '" style="font-weight:bold;color: ' .. color .. ';"|' .. value .. '\n'
    -- Вызов функции из модуля Entity Lookup для получения имени элемента
end
    local itemName = frame:preprocess('{{#invoke:Entity Lookup|getname|' .. itemId .. '}}')
 
    -- Обработка шаблона Anchor с помощью frame:preprocess
    local anchor = frame:preprocess('{{Anchor|' .. anchorName .. '}}')


    -- Вычисляем цвет рамки (чуть темнее заданного цвета)
function p.main(frame)
    local borderColor = darkenColor(color)
local dataCache = loadData()
local id = frame.args.id or "" -- ID предмета
local itemData = findDataById(dataCache, id)


    -- Создание HTML
-- Получаем защитные значения из armor, если они присутствуют
    local div = mw.html.create('div')
local armor = itemData and itemData.Armor and itemData.Armor.modifiers and itemData.Armor.modifiers.coefficients
    div:addClass(divClass)
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 table = mw.html.create('table')
local sprintModifier = itemData and itemData.ClothingSpeedModifier and itemData.ClothingSpeedModifier.sprintModifier
    local row = table:tag('tr')
local walkModifier = itemData and itemData.ClothingSpeedModifier and itemData.ClothingSpeedModifier.walkModifier
local fireProtection = itemData and itemData.FireProtection and itemData.FireProtection.reduction
local speedDescription = ""


    -- Добавление ячеек в строку
-- Формируем сообщение в зависимости от значений sprintModifier и walkModifier
    row
if sprintModifier and walkModifier then
        :tag('th')
    if sprintModifier == 1 and walkModifier == 1 then
        :attr('style', 'background-color: ' .. color .. ';border-top: 1px solid ' .. borderColor .. ';border-bottom: 1px solid ' .. borderColor .. ';border-left: 2px solid ' .. borderColor .. ';')
        speedDescription = ""
        :wikitext(anchor .. imageTooltip .. '<br>' .. itemName)
    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


    row
-- Формируем сообщение для огневой защиты, если значение присутствует
        :tag('td')
local fireProtectionDescription = fireProtection and
        :attr('style', 'font-weight:bold;color: crimson;background-color: ' .. backgroundColor)
"* Имеет огневую защиту в <span style=\"color:OrangeRed\">'''" .. round((1 - fireProtection) * 100) .. " %'''</span>\n" or ""
        :wikitext(protBlunt)


    row
-- Описание и местоположение
        :tag('td')
local description = (frame.args.description or "") .. '\n' .. speedDescription .. fireProtectionDescription -- Описание
        :attr('style', 'font-weight:bold;color: indianred;background-color: ' .. backgroundColor)
local location = frame.args.location or "" -- Местонахождение
        :wikitext(protSlash)
local created = frame.args.created or "" -- Создание


    row
local anchorName = frame.args.anchorName or "" -- Название якоря
        :tag('td')
local backgroundColor = frame.args.backgroundColor or "" -- Цвет фона первой ячейки
        :attr('style', 'font-weight:bold;color: darksalmon;background-color: ' .. backgroundColor)
local class = frame.args.class or "" -- Класс
        :wikitext(protPiercing)


    row
-- Формирование строк для ячеек таблицы
        :tag('td')
local out = ''
        :attr('style', 'font-weight:bold;color: orange;background-color: ' .. backgroundColor)
out = out .. '!class="' .. class .. '" style="background-color: ' .. backgroundColor .. ';"|' .. frame:preprocess('{{Anchor|' .. anchorName .. '}}')  
        :wikitext(protHeat)
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'


    row
-- Используем функцию для формирования строк защиты
        :tag('td')
out = out .. createProtectionRow(class, "crimson", protBlunt)
        :attr('style', 'font-weight:bold;color: plum;background-color: ' .. backgroundColor)
out = out .. createProtectionRow(class, "indianred", protSlash)
        :wikitext(protRadiation)
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)


    row
out = out .. '|class="' .. class .. '" style=""|\n' .. description .. '\n'
        :tag('td')
out = out .. '|class="' .. class .. '" style=""|\n'
        :attr('style', 'font-weight:bold;color: limegreen;background-color: ' .. backgroundColor)
        :wikitext(protCaustic)


    row
        :tag('td')
        :attr('style', 'font-weight:bold;color: tan;background-color: ' .. backgroundColor)
        :wikitext(protExplosion)


    row
-- Проверка класса на "spacesuit-helmet"
        :tag('td')
if class == "spacesuit-helmet" then
        :attr('style', 'background-color: ' .. backgroundColor)
out = out .. frame:preprocess("{{FrameText|color = #bcceff|border-color = #4c4c61|content = Находится в скафандре}}")
        :wikitext(description)
-- Местоположение
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


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


    -- Вставка таблицы в div
out = out .. '|-\n'
    div:node(table)


    return tostring(div)
return out
end
end


return p
return p