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

мНет описания правки
мНет описания правки
 
(не показано 78 промежуточных версий этого же участника)
Строка 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 splitIds(idsStr)
local function kelvinToCelsius(k)
     local ids = {}
     return k - 273.15
     for id in string.gmatch(idsStr, '([^,]+)') do
end
         table.insert(ids, mw.text.trim(id))
 
local function findSeedById(id, data)
     for _, seed in ipairs(data) do
         if seed.id == id then
            return seed
        end
     end
     end
     return ids
     return nil
end
end


local function buildCellEvent(name, eventID, image)
local function formatCharacteristics(seed)
     local cell = '<div style="text-align:center;">'
     local parts = {
    cell = cell .. "" .. name .. "<br>"
        ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1),
    cell = cell .. '[[File:' .. image .. '|64px]]'
        ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield),
     cell = cell .. '</div>'
        ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan),
    return cell
        ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation),
        ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production),
        ("[[Гидропоника#Стадии роста|Стадии роста]]: %s"):format(seed.growthStages or 6),
    }
     return table.concat(parts, '<br>')
end
end


local function buildCharacteristicsList(frame, stationEvent)
local function formatConditions(seed)
     local list = ""
     local parts = {
    local characteristics = {
         ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5),
         {"Вес", "Вес события в системе случайных событий (чем выше, тем чаще случается)", stationEvent.weight},
         ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75),
        {"Мин. игроков", "Минимальное количество игроков для начала события", stationEvent.minimumPlayers},
         ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)),
         {"Время старта", "Время с которого событие может начаться", (stationEvent.earliestStart and stationEvent.earliestStart .. " сек.")},
         {"Длительность", "Длительность события в секундах", (stationEvent.duration and stationEvent.duration .. " сек.")}
     }
     }
     for _, char in ipairs(characteristics) do
     return table.concat(parts, '<br>')
        local value = char[3] or "Нет"
end
        list = list .. "- " .. frame:expandTemplate{
 
            title = "AltTooltip",
local function formatHarvestType(seed)
            args = { char[1], char[2] }
    return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
         } .. ": " .. value .. "<br>"
end
local function formatHarvestType(seed)
    local harvestRepeat = seed.harvestRepeat
    if harvestRepeat == "Repeat" then
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
    elseif harvestRepeat == "SelfHarvest" then
        return "[[Гидропоника#Тип урожая|Самосбор]]"
    else
         return "[[Гидропоника#Тип урожая|Однолетнее]]"
     end
     end
    return list
end
end


function p.eventStation(frame)
local function formatChemicals(seed)
     local args = frame.args
    if not seed.chemicals then return "-" end
    local idsStr = args.id or ""
     local list = {}
    local name = args.name or ""
    for chemId, vals in pairs(seed.chemicals) do
    local image = args.image or "test.png"
        local entry = chemData[chemId]
     local description = args.description or "Нет описания"
        local chemName = entry and entry.name or chemId
     local out = ""
        table.insert(list, string.format(
     local ids = splitIds(idsStr)
            "<li>[[Химия#chem_%s|%s]] (мин: %s, макс: %s, дел: %s)</li>",
   
            chemId, chemName, vals.Min or 0, vals.Max or 0, vals.PotencyDivisor or 1
     for _, searchId in ipairs(ids) do
        ))
         for _, event in ipairs(eventData) do
    end
            if event.id == searchId then
     return "<ul>" .. table.concat(list) .. "</ul>"
                local cellEvent = buildCellEvent(name, image)
end
                local advert = (event.StationEvent and event.StationEvent.startAnnouncement) or "Нет оповещения"
 
                 local characteristicsList = buildCharacteristicsList(frame, event.StationEvent or {})
local function formatMutations(seed, data)
               
     if not seed.mutationPrototypes then return "-" end
                out = out .. "|-\n"
     local list = {}
                out = out .. "! " .. cellEvent .. "\n"
     for _, mu in ipairs(seed.mutationPrototypes) do
                out = out .. "| {{#invoke:Ftl|main|translation|" .. advert .. "}}\n"
         local target = findSeedById(mu, data)
                out = out .. "| " .. description .. "\n"
        if target and target.productPrototypes then
                out = out .. "| " .. characteristicsList .. "\n"
            for _, prod in ipairs(target.productPrototypes) do
                break
                 table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod))
             end
             end
         end
         end
     end
     end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


     return frame:preprocess(out)
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
end


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


                local characteristicsList = buildCharacteristicsList(frame, event.StationEvent or {})
    if mode  == "growth" then
                out = out .. "|-\n"
        return formatCharacteristics(seed)
                out = out .. "! " .. cellEvent .. "\n"
    elseif mode  == "conditions" then
                out = out .. "| " .. advert .. "\n"
        return formatConditions(seed)
                out = out .. "| " .. description .. "\n"
    elseif mode  == "harvest" then
                out = out .. "| " .. characteristicsList .. "\n"
        return formatHarvestType(seed)
                out = out .. "| " .. giftsCell .. "\n"
    elseif mode  == "chemicals" then
                break
        return formatChemicals(seed)
            end
    elseif mode  == "mutations" then
         end
        return formatMutations(seed, seedsData)
    else
         return ""
     end
     end
    return frame:preprocess(out)
end
end


return p
return p