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

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


local eventData = mw.loadData("Модуль:IanComradeBot/prototypes/StationEvent.json/data")
-- Загрузка данных
local cargoData = mw.loadData("Модуль:IanComradeBot/prototypes/cargo.json/data")
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")


local function buildCellEvent(name, image, id)
local function kelvinToCelsius(k)
     local cell = '<div style="text-align:center;">'
     return k - 273.15
    cell = cell .. name .. "<br>"
    cell = cell .. "<span style='color:#adadad'>" .. id .. "</span><br>"
    cell = cell .. '[[File:' .. image .. '|64px]]'
    cell = cell .. '</div>'
    return cell
end
end


local function buildCharacteristicsList(frame, stationEvent)
local function findSeedById(id, data)
     local characteristics = {
     for _, seed in ipairs(data) do
         {
         if seed.id == id then
            label = "Вес",
             return seed
            tooltip = "Вес события в системе случайных событий (чем выше, тем чаще случается)",
         end
             value = stationEvent.weight
    end
         },
    return nil
        {
end
            label = "Мин. игроков",
 
            tooltip = "Минимальное количество игроков для начала события",
local function formatCharacteristics(seed)
            value = stationEvent.minimumPlayers
    local parts = {
        },
        ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1),
        {
        ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield),
            label = "Время старта",
        ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan),
            tooltip = "Время с которого событие может начаться",
         ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation),
            value = stationEvent.earliestStart and (stationEvent.earliestStart .. " сек.") or nil
        ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production),
        },
        ("[[Гидропоника#Стадии роста|Стадии роста]]: %s"):format(seed.growthStages or 6),
         {
            label = "Длительность",
            tooltip = "Длительность события в секундах",
            value = stationEvent.duration and (stationEvent.duration .. " сек.") or nil
        }
     }
     }
    return table.concat(parts, '<br>')
end


     local list = {}
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


     for _, char in ipairs(characteristics) do
local function formatHarvestType(seed)
        local value = char.value or "нет"
     return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
        local tooltip = frame:expandTemplate{
end
            title = "AltTooltip",
local function formatHarvestType(seed)
            args = { char.label, char.tooltip }
    local harvestRepeat = seed.harvestRepeat
         }
    if harvestRepeat == "Repeat" then
         table.insert(list, string.format("- %s: %s<br>", tooltip, value))
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
    elseif harvestRepeat == "SelfHarvest" then
         return "[[Гидропоника#Тип урожая|Самосбор]]"
    else
         return "[[Гидропоника#Тип урожая|Однолетнее]]"
     end
     end
end


     return table.concat(list)
local function formatChemicals(seed)
    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
     return "<ul>" .. table.concat(list) .. "</ul>"
end
end


function p.eventStation(frame)
local function formatMutations(seed, data)
     local args = frame.args
     if not seed.mutationPrototypes then return "-" end
    local searchId = args.id or ""
     local list = {}
     local name = args.name or ""
     for _, mu in ipairs(seed.mutationPrototypes) do
    local image = args.image or ""
         local target = findSeedById(mu, data)
    local description = args.description or "Нет описания"
        if target and target.productPrototypes then
    local out = ""
             for _, prod in ipairs(target.productPrototypes) do
   
                table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod))
     for _, event in ipairs(eventData) do
         if event and event.id and event.id == searchId then
            local cellEvent = buildCellEvent(name, image, searchId)
            local advert = (event.StationEvent and event.StationEvent.startAnnouncement) or ""
             local characteristicsList = buildCharacteristicsList(frame, event.StationEvent or {})
 
            out = out .. "|-\n"
            out = out .. "! " .. cellEvent .. "\n"
            if advert ~= "" then
                out = out .. "| {{#invoke:Ftl|main|translation|" .. advert .. "}}\n"
            else
                out = out .. "| Происходит без объявления\n"
             end
             end
            out = out .. "| " .. description .. "\n"
            out = out .. "| " .. characteristicsList .. ""
            break
         end
         end
     end
     end
    return "<ul>" .. table.concat(list) .. "</ul>"
end
local function generateHeader()
    return [[
{| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;"
! 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


     return frame:preprocess(out)
local function generateFooter()
     return "|}"
end
end


function p.eventCargo(frame)
function p.table(frame)
     local args = frame.args
     local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
    local searchId = args.id or ""
     local rows = {}
    local name = args.name or ""
 
     local image = args.image or ""
     for _, seed in ipairs(data) do
    local out = ""
         local prodId = seed.productPrototypes[1]
   
        local seedId = seed.packetPrototype
     for _, event in ipairs(eventData) do
        local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)
         if event and event.id and event.id == searchId then
 
            local cellEvent = buildCellEvent(name, image, searchId)
        local anchor  = string.format('{{anchor|%s}}', seedName)
            local cargo = event.CargoGiftsRule or {}
        local fruitImg = string.format(
            local sender = cargo.sender or "Нет отправителя"
             '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}',
             local cargoDescription = cargo.description or "Нет описания"
             prodId, seedName
             local dest = cargo.dest or "Нет получателя"
        )
             local advert = "Поздравляем! {{#invoke:Ftl|main|translation|" .. sender .. "}} решили отправить {{#invoke:Ftl|main|translation|" .. cargoDescription .. "}} {{#invoke:Ftl|main|translation|" .. dest .. "}} станции. Всё прибудет со следующей партией груза."
        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 giftsCell = ""
        local colGrowth    = formatCharacteristics(seed)
            if cargo.gifts then
        local colConditions = formatConditions(seed)
                for giftId, giftValue in pairs(cargo.gifts) do
        local colHarvest    = formatHarvestType(seed)
                    local productFound = nil
        local colChemicals  = formatChemicals(seed)
                    for _, cargoItem in ipairs(cargoData) do
        local colMutations  = formatMutations(seed, data)
                        if cargoItem.id == giftId then
                            productFound = cargoItem.product
                            break
                        end
                    end
                    if productFound then
                        giftsCell = giftsCell .. "- [[Таблица грузов#{{#invoke:Entity Lookup|getname|" .. productFound .. "}}|{{#invoke:Entity Lookup|getname|" .. productFound .. "}}]] x" .. giftValue .. "<br>"
                    else
                        giftsCell = giftsCell .. "Ошибка: id продукта не найден."
                    end
                end
            else
                giftsCell = "Нет подарков"
            end


            local characteristicsList = buildCharacteristicsList(frame, event.StationEvent or {})
        local row = frame:preprocess(string.format(
             out = out .. "|-\n"
             [[|-
             out = out .. "! " .. cellEvent .. "\n"
             ! %s
             out = out .. "| " .. advert .. "\n"
            ! %s
             out = out .. "| " .. giftsCell .. "\n"
            ! %s
             out = out .. "| " .. characteristicsList .. ""
            | %s
             break
            | %s
         end
             | %s
             | %s
             | %s ]],
            fruitImg, seedImg, plantImg,
            colGrowth, colConditions, colHarvest,
             colChemicals, colMutations
         ))
        table.insert(rows, row)
     end
     end


     return frame:preprocess(out)
     return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter()
end
 
function p.main(frame)
    local args = frame.args
    local id = args[1]
    local mode  = mw.text.trim(args[2] or ""):lower()
    local seed = findSeedById(id, seedsData)
    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
        return ""
    end
end
end


return p
return p