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

Материал из Space Station 14 Вики
Нет описания правки
мНет описания правки
(не показано 165 промежуточных версий этого же участника)
Строка 1: Строка 1:
-- Загрузка данных
local spriteData = mw.loadData("Модуль:IanComradeBot/prototypes/entity sprite.json/data")
local p = {}
local p = {}


-- Функция загрузки данных из JSON-страницы
-- Функция для получения таблицы данных
local function loadData(filePath)
function p.getData()
     local page = mw.title.new(filePath)
    return spriteData
    if not page then
end
         return nil
 
-- Общая функция нечувствительного к регистру поиска поля
local function findFieldInsensitive(tbl, fieldName)
     for key, value in pairs(tbl) do
        if type(key) == "string" and mw.ustring.lower(key) == mw.ustring.lower(fieldName) then
            return value
         end
     end
     end
     local content = page:getContent()
    return nil
     if not content then
end
         return nil
 
-- Функция получения пути спрайта
local function getSpritePath(entry)
     local spriteBlock = findFieldInsensitive(entry, "Sprite") or findFieldInsensitive(entry, "Icon")
     if spriteBlock then
        if spriteBlock.sprite then
            return spriteBlock.sprite
         elseif spriteBlock.layers then
            for _, layer in pairs(spriteBlock.layers) do
                if layer.sprite then
                    return layer.sprite
                end
            end
        end
     end
     end
     return mw.text.jsonDecode(content)
     return nil
end
end


-- Функция генерации текста для одного элемента JSON
-- Функция получения state
local function generateTemplate(entry)
local function getSpriteState(entry)
     if not entry.id or not entry.Sprite or not entry.Sprite.sprite then
     local spriteBlock = findFieldInsensitive(entry, "Sprite")
         return nil
    if spriteBlock then
        if spriteBlock.state then
            return spriteBlock.state
        elseif spriteBlock.layers then
            for _, layer in pairs(spriteBlock.layers) do
                if layer.state then
                    return layer.state
                end
            end
        end
    end
 
    local iconBlock = findFieldInsensitive(entry, "Icon")
    if iconBlock and iconBlock.state then
         return iconBlock.state
     end
     end
   
 
    local template =
     return nil
        "== Краткое описание ==\n" ..
        "{{Файл\n" ..
        "|Описание = \n" ..
        "|Id      = %s\n" ..
        "|Сервера  = {{abb|SS14}}\n" ..
        "|Источник = \n" ..
        "|Путь    = Resources/Textures/%s\n" ..
        "|Теги    = \n" ..
        "}}\n\n" ..
        "== Лицензирование ==\n" ..
        "{{CC-BY-SA-3.0}}\n"
   
     return string.format(template, entry.id, entry.Sprite.sprite)
end
end


-- Функция для обёртки текста в HTML с классом
-- Функция генерации шаблона по записи
local function wrapInClass(content, className)
function p.getSprite(frame)
     return string.format('<div class="%s">%s</div>', className, content)
     local id = frame.args[1]
end
    if not id then return "Ошибка: не указан ID" end
 
    for _, entry in ipairs(spriteData) do
        if entry.id == id then
            return getSpritePath(entry) or "Ошибка: спрайт не найден"
        end
    end


-- Функция для добавления кнопки копирования
     return "Ошибка: ID не найден"
local function addCopyIcon(content)
     return content .. '<div class="copy-icon">📋</div>'
end
end


-- Основная функция модуля
-- Основная функция модуля
function p.main(frame)
function p.main(frame)
     -- Загрузка данных из указанного JSON-файла
     local mode = frame.args[1]
     local data = loadData("User:IanComradeBot/prototypes/entity sprite.json")
     local id = frame.args[2]
     if not data or type(data) ~= "table" then
     if not mode or not id then
         return "Ошибка: Невозможно загрузить данные из JSON."
         return "Ошибка: отсутствует режим или ID"
     end
     end
   
 
     -- Создание результата
     if mode == "image" then
    local result = {}
        for _, entry in ipairs(spriteData) do
    for _, entry in ipairs(data) do
            if entry.id == id then
        local template = generateTemplate(entry)
                local sprite = getSpritePath(entry)
        if template then
                if sprite then
             -- Оборачиваем текст в класс
                    return sprite
            local wrappedTemplate = wrapInClass(template, "entity-sprite__strings")
                else
             -- Добавляем кнопку копирования
                    return "Ошибка: спрайт не найден"
             local finalTemplate = addCopyIcon(wrappedTemplate)
                end
             table.insert(result, finalTemplate)
             end
        end
        return "Ошибка: ID не найден"
    elseif mode == "path" then
        for _, entry in ipairs(spriteData) do
             if getSpritePath(entry) == id then
                return entry.id
             end
        end
        return "Ошибка: путь не найден"
    elseif mode == "state" then
        for _, entry in ipairs(spriteData) do
             if entry.id == id then
                local state = getSpriteState(entry)
                if state then
                    return "(state: " .. state .. ")"
                else
                    return ""
                end
            end
         end
         end
        return "Ошибка: ID не найден"
    else
        return "Ошибка: неизвестный режим"
     end
     end
   
    -- Возврат собранного результата
    return table.concat(result, "\n")
end
end


return p
return p

Версия от 16:11, 7 апреля 2025

Шаблон:Entity Sprite


-- Загрузка данных
local spriteData = mw.loadData("Модуль:IanComradeBot/prototypes/entity sprite.json/data")

local p = {}

-- Функция для получения таблицы данных
function p.getData()
    return spriteData
end

-- Общая функция нечувствительного к регистру поиска поля
local function findFieldInsensitive(tbl, fieldName)
    for key, value in pairs(tbl) do
        if type(key) == "string" and mw.ustring.lower(key) == mw.ustring.lower(fieldName) then
            return value
        end
    end
    return nil
end

-- Функция получения пути спрайта
local function getSpritePath(entry)
    local spriteBlock = findFieldInsensitive(entry, "Sprite") or findFieldInsensitive(entry, "Icon")
    if spriteBlock then
        if spriteBlock.sprite then
            return spriteBlock.sprite
        elseif spriteBlock.layers then
            for _, layer in pairs(spriteBlock.layers) do
                if layer.sprite then
                    return layer.sprite
                end
            end
        end
    end
    return nil
end

-- Функция получения state
local function getSpriteState(entry)
    local spriteBlock = findFieldInsensitive(entry, "Sprite")
    if spriteBlock then
        if spriteBlock.state then
            return spriteBlock.state
        elseif spriteBlock.layers then
            for _, layer in pairs(spriteBlock.layers) do
                if layer.state then
                    return layer.state
                end
            end
        end
    end

    local iconBlock = findFieldInsensitive(entry, "Icon")
    if iconBlock and iconBlock.state then
        return iconBlock.state
    end

    return nil
end

-- Функция генерации шаблона по записи
function p.getSprite(frame)
    local id = frame.args[1]
    if not id then return "Ошибка: не указан ID" end

    for _, entry in ipairs(spriteData) do
        if entry.id == id then
            return getSpritePath(entry) or "Ошибка: спрайт не найден"
        end
    end

    return "Ошибка: ID не найден"
end

-- Основная функция модуля
function p.main(frame)
    local mode = frame.args[1]
    local id = frame.args[2]
    if not mode or not id then
        return "Ошибка: отсутствует режим или ID"
    end

    if mode == "image" then
        for _, entry in ipairs(spriteData) do
            if entry.id == id then
                local sprite = getSpritePath(entry)
                if sprite then
                    return sprite
                else
                    return "Ошибка: спрайт не найден"
                end
            end
        end
        return "Ошибка: ID не найден"
    elseif mode == "path" then
        for _, entry in ipairs(spriteData) do
            if getSpritePath(entry) == id then
                return entry.id
            end
        end
        return "Ошибка: путь не найден"
    elseif mode == "state" then
        for _, entry in ipairs(spriteData) do
            if entry.id == id then
                local state = getSpriteState(entry)
                if state then
                    return "(state: " .. state .. ")"
                else
                    return ""
                end
            end
        end
        return "Ошибка: ID не найден"
    else
        return "Ошибка: неизвестный режим"
    end
end

return p