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

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


local p = {}
-- Загрузка данных
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
 
local function kelvinToCelsius(k)
    return k - 273.15
end


--- Функция main принимает два параметра:
local function findSeedById(id, data)
--- @param mode string  "melee" или "attackRate"
     for _, seed in ipairs(data) do
--- @param id string    идентификатор оружия
        if seed.id == id then
function p.main(mode, id)
            return seed
     -- Проверка на наличие id
         end
    if id == nil then
         return "Ошибка: не задан параметр id."
     end
     end
    return nil
end
local function formatCharacteristics(seed)
    local parts = {
        ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1),
        ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield),
        ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan),
        ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation),
        ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production),
        ("[[Гидропоника#Стадии роста|Стадии роста]]: %s"):format(seed.growthStages or 6),
    }
    return table.concat(parts, '<br>')
end
local function formatConditions(seed)
    local parts = {
        ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5),
        ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75),
        ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)),
    }
    return table.concat(parts, '<br>')
end


    local entry = nil
local function formatHarvestType(seed)
     -- Поиск записи по заданному id (предполагается, что weaponData — массив записей)
     return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
     for _, weapon in ipairs(weaponData) do
end
        if weapon.id == id then
local function formatHarvestType(seed)
            entry = weapon
     local harvestRepeat = seed.harvestRepeat
            break
    if harvestRepeat == "Repeat" then
         end
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
    elseif harvestRepeat == "SelfHarvest" then
        return "[[Гидропоника#Тип урожая|Самосбор]]"
    else
         return "[[Гидропоника#Тип урожая|Однолетнее]]"
     end
     end
end


     if not entry then
local function formatChemicals(seed)
        return "Оружие с id '" .. tostring(id) .. "' не найдено."
     if not seed.chemicals then return "-" end
    local list = {}
    for chemId, vals in pairs(seed.chemicals) do
        local entry = chemData[chemId]
        local chemName = entry and entry.name or chemId
        table.insert(list, string.format(
            "<li>[[Химия#chem_%s|%s]] (мин: %s, макс: %s, дел: %s)</li>",
            chemId, chemName, vals.Min or 0, vals.Max or 0, vals.PotencyDivisor or 1
        ))
     end
     end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


     if mode == "melee" then
local function formatMutations(seed, data)
         local melee = entry.MeleeWeapon
     if not seed.mutationPrototypes then return "-" end
         if not melee then
    local list = {}
             return "Нет данных о MeleeWeapon для оружия '" .. tostring(id) .. "'."
    for _, mu in ipairs(seed.mutationPrototypes) do
         local target = findSeedById(mu, data)
         if target and target.productPrototypes then
             for _, prod in ipairs(target.productPrototypes) do
                table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod))
            end
         end
         end
    end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


        local oneHandDamage = melee.damage and melee.damage.types
local function generateHeader()
        if not oneHandDamage then
    return [[
            return "Нет данных о повреждениях (MeleeWeapon.damage.types) для оружия '" .. tostring(id) .. "'."
{| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;"
        end
! rowspan="2" style="width:10%;" | Плод
! rowspan="2" class="unsortable" style="width:5%;" | Семена
! rowspan="2" class="unsortable" style="width:5%;" | Растение
! colspan="3" class="unsortable" style="width:30%;" id="no-highlight" | Характеристики
! rowspan="2" class="unsortable" style="width:30%;" | Содержит вещества
! rowspan="2" style="width:20%;" | Мутации
|-
! style="width:10%;" class="unsortable" | Рост
! style="width:10%;" class="unsortable" | Условия
! style="width:5%;" class="unsortable" | Тип сбора
]]
end
 
local function generateFooter()
    return "|}"
end


        local twoHandDamage = entry.DamageOtherOnHit
function p.table(frame)
                                and entry.DamageOtherOnHit.damage
    local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
                                and entry.DamageOtherOnHit.damage.types
    local rows = {}


         local lines = {}
    for _, seed in ipairs(data) do
         local prodId = seed.productPrototypes[1]
        local seedId = seed.packetPrototype
        local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)


         if twoHandDamage then
         local anchor  = string.format('{{anchor|%s}}', seedName)
             -- Секция одноручного хвата
        local fruitImg = string.format(
             table.insert(lines, "В одноручном хвате:")
             '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}',
             for dmgType, value in pairs(oneHandDamage) do
             prodId, seedName
                table.insert(lines, value .. " " .. dmgType)
        )
             end
        local seedImg  = string.format(
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}',
             seedId, seedName
        )
        local plantImg = string.format(
            '{{Предмет|%s-harvest|size=64px|l=|link=%s}}',
             seedId, seedName
        )


            -- Секция двуручного хвата
        local colGrowth    = formatCharacteristics(seed)
            table.insert(lines, "В двуручном хвате:")
        local colConditions = formatConditions(seed)
            for dmgType, value in pairs(twoHandDamage) do
        local colHarvest    = formatHarvestType(seed)
                -- Если тип присутствует в одноручном хвате, выводим так же
        local colChemicals  = formatChemicals(seed)
                if oneHandDamage[dmgType] then
         local colMutations  = formatMutations(seed, data)
                    table.insert(lines, value .. " " .. dmgType)
                else
                    table.insert(lines, value .. " " .. dmgType)
                end
            end
         else
            -- Если нет данных для двуручного хвата, выводим только одноручные повреждения
            for dmgType, value in pairs(oneHandDamage) do
                table.insert(lines, value .. " " .. dmgType)
            end
        end


         return table.concat(lines, "<br />")
         local row = frame:preprocess(string.format(
            [[|-
            ! %s
            ! %s
            ! %s
            | %s
            | %s
            | %s
            | %s
            | %s ]],
            fruitImg, seedImg, plantImg,
            colGrowth, colConditions, colHarvest,
            colChemicals, colMutations
        ))
        table.insert(rows, row)
    end


     elseif mode == "attackRate" then
     return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter()
        local melee = entry.MeleeWeapon
end
        if not melee then
            return "Нет данных о MeleeWeapon для оружия '" .. tostring(id) .. "'."
        end


        -- Если attackRate отсутствует, возвращаем "1"
function p.main(frame)
        if melee.attackRate then
    local args = frame.args
            return tostring(melee.attackRate)
    local id = args[1]
        else
    local mode  = mw.text.trim(args[2] or ""):lower()
            return "1"
    local seed = findSeedById(id, seedsData)
        end
    if not seed then return "" end


    if mode  == "growth" then
        return formatCharacteristics(seed)
    elseif mode  == "conditions" then
        return formatConditions(seed)
    elseif mode  == "harvest" then
        return formatHarvestType(seed)
    elseif mode  == "chemicals" then
        return formatChemicals(seed)
    elseif mode  == "mutations" then
        return formatMutations(seed, seedsData)
     else
     else
         return "Неверный режим: " .. tostring(mode)
         return ""
     end
     end
end
end


return p
return p