|
|
| (не показано 214 промежуточных версий этого же участника) |
| Строка 1: |
Строка 1: |
| | local p = {} |
| | |
| -- Загрузка данных | | -- Загрузка данных |
| local itemData = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data") | | local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data") |
| | local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data") |
|
| |
|
| local p = {} | | local function kelvinToCelsius(k) |
| | | return k - 273.15 |
| -- Функция для загрузки данных
| |
| local loadData = function(filePath)
| |
| local page = mw.title.new(filePath)
| |
| local content = page:getContent()
| |
| return content and mw.text.jsonDecode(content) or nil | |
| end | | end |
|
| |
|
| -- Функция processRolls для преобразования диапазона
| | local function findSeedById(id, data) |
| local processRolls = function(rolls) | | for _, seed in ipairs(data) do |
| local result = "" | | if seed.id == id then |
| if rolls and rolls.range then
| | return seed |
| -- Если указан range
| |
| local min, max = rolls.range:match("(%d+),%s*(%d+)")
| |
| min, max = tonumber(min), tonumber(max) | |
| if min and max then
| |
| result = result .. string.format('[%d-%d]', min + 1, max + 1) | |
| else
| |
| result = result .. 'Некорректный формат для range.'
| |
| end | | end |
| elseif rolls and rolls.value then
| |
| -- Если указано value
| |
| result = result .. string.format('[%d]', rolls.value)
| |
| else
| |
| result = result .. 'Не указан параметр rolls.'
| |
| end | | end |
| return result | | return nil |
| end | | end |
|
| |
|
| -- Локальные функции
| | local function formatCharacteristics(seed) |
| local findDataById, formatContent, getContentsOutput, processNestedSelectors, getTableOutput, getContainedOutput, getChemOutput, handleGroupSelector, handleAllSelector, handleNestedSelector
| | local parts = { |
| | | ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1), |
| -- Функция для создания хэш-таблицы для быстрого поиска по ID
| | ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield), |
| local function buildIndex(itemData) | | ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan), |
| if not itemData then return {} end
| | ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation), |
| local index = {} | | ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production), |
| for _, item in ipairs(itemData) do
| | ("[[Гидропоника#Стадии роста|Стадии роста]]: %s"):format(seed.growthStages or 6), |
| index[item.id] = item | | } |
| end | | return table.concat(parts, '<br>') |
| return index | |
| end | | end |
|
| |
|
| -- Поиск данных по ID через индекс
| | local function formatConditions(seed) |
| findDataById = function(itemDataIndex, id)
| | local parts = { |
| if not itemDataIndex then return nil end | | ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5), |
| for _, item in ipairs(itemDataIndex) do
| | ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75), |
| if item.id == id then
| | ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)), |
| return item
| | } |
| end
| | return table.concat(parts, '<br>') |
| end
| |
| end | | end |
|
| |
|
| -- Форматирование содержимого
| | local function formatHarvestType(seed) |
| formatContent = function(content)
| | return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-" |
| if not content.id then | |
| return "Ошибка: отсутствует id у элемента."
| |
| end
| |
| | |
| local name = string.format('{{#invoke:Entity Lookup|getname|%s}}', content.id)
| |
| local image = string.format('%s.png', content.id)
| |
| local amount = (content.amount and content.amount ~= 1) and string.format(" [%d]", content.amount) or ""
| |
| local prob = ""
| |
| | |
| if content.weight then
| |
| content.prob = content.weight / 100
| |
| end
| |
| | |
| if content.prob then
| |
| prob = string.format(" <div>%s%%</div>", content.prob * 100 >= 1 and math.floor(content.prob * 100) or content.prob * 100)
| |
| end
| |
| | |
| return string.format(
| |
| '{{LinkСard|SideStyle=1|background-color=#cbcbff0a|image=%s|name=%s%s%s {{#invoke:Prototypes/Хранилище/Предмет|main|framing|contained|%s}} }}',
| |
| image, name, amount, prob, content.id
| |
| )
| |
| end | | end |
| | | local function formatHarvestType(seed) |
| -- Получение содержимого через таблицу
| | local harvestRepeat = seed.harvestRepeat |
| getContentsOutput = function(contents)
| | if harvestRepeat == "Repeat" then |
| local result = "" | | return "[[Гидропоника#Тип урожая|Многолетнее]]" |
| for _, content in ipairs(contents) do
| | elseif harvestRepeat == "SelfHarvest" then |
| result = result .. formatContent(content)
| | return "[[Гидропоника#Тип урожая|Самосбор]]" |
| end
| | else |
| return result
| | return "[[Гидропоника#Тип урожая|Однолетнее]]" |
| end
| |
| | |
| -- Обработка вложенных таблиц
| |
| processNestedSelectors = function(children, visited)
| |
| visited = visited or {}
| |
| if not children or #children == 0 then return "" end | |
| | |
| local result = "" | |
| | |
| for _, child in ipairs(children) do
| |
| if child.id then | |
| if not visited[child.id] then
| |
| result = result .. formatContent(child)
| |
| end
| |
| elseif child["!type"] == "NestedSelector" then
| |
| result = result .. handleNestedSelector(child, true, visited)
| |
| elseif child["!type"] == "GroupSelector" then | |
| result = result .. handleGroupSelector(child, visited)
| |
| end
| |
| end | | end |
|
| |
| return result
| |
| end | | end |
|
| |
|
| -- Обработка таблиц
| | local function formatChemicals(seed) |
| getTableOutput = function(tableId, visited)
| | if not seed.chemicals then return "-" end |
| visited = visited or {} | | local list = {} |
| | | for chemId, vals in pairs(seed.chemicals) do |
| if visited[tableId] then
| | local entry = chemData[chemId] |
| return '' | | 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>" |
| visited[tableId] = true | |
| | |
| local tableData = loadData('User:IanComradeBot/prototypes/table.json')
| |
| local tableDataIndex = findDataById(tableData, tableId)
| |
| | |
| if not tableDataIndex then return 'Таблица не найдена.' end
| |
| | |
| if tableDataIndex['!type:GroupSelector'] then
| |
| return handleGroupSelector(tableDataIndex['!type:GroupSelector'], visited)
| |
| elseif tableDataIndex['!type:AllSelector'] then
| |
| return processNestedSelectors(tableDataIndex['!type:AllSelector'].children, visited)
| |
| end
| |
| | |
| return 'Таблица не содержит элементов.'
| |
| end | | end |
|
| |
|
| -- Формирование списка содержащихся предметов или таблиц
| | local function formatMutations(seed, data) |
| getContainedOutput = function(itemData, id, visited)
| | if not seed.mutationPrototypes then return "-" end |
| visited = visited or {}
| | local list = {} |
| | | for _, mu in ipairs(seed.mutationPrototypes) do |
| if visited[id] then
| | local target = findSeedById(mu, data) |
| return ''
| | if target and target.productPrototypes then |
| end
| | for _, prod in ipairs(target.productPrototypes) do |
| | | table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod)) |
| visited[id] = true
| |
| | |
| local item = findDataById(itemData, id)
| |
| if not item then return '' end | |
| | |
| local result = "" | |
| | |
| -- Обработка StorageFill | |
| if item.StorageFill and item.StorageFill.contents then
| |
| result = result .. getContentsOutput(item.StorageFill.contents)
| |
| -- Обработка EntityTableContainerFill
| |
| elseif item.EntityTableContainerFill and item.EntityTableContainerFill.containers then
| |
| local containers = item.EntityTableContainerFill.containers | |
| | |
| -- Обработка entity_storage
| |
| if containers.entity_storage then | |
| if containers.entity_storage.children then | |
| result = result .. processNestedSelectors(containers.entity_storage.children, visited) | |
| end
| |
| if containers.entity_storage.tableId then
| |
| result = result .. getTableOutput(containers.entity_storage.tableId, visited)
| |
| end | | end |
| end
| |
|
| |
| -- Обработка storagebase
| |
| if containers.storagebase and containers.storagebase.tableId then
| |
| result = result .. getTableOutput(containers.storagebase.tableId, visited)
| |
| end | | end |
| end | | end |
| | | return "<ul>" .. table.concat(list) .. "</ul>" |
| return result | |
| end | | end |
|
| |
|
| -- Обработка AllSelector
| | local function generateHeader() |
| handleAllSelector = function(allSelector)
| | return [[ |
| if not allSelector.children then return '' end | | {| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;" |
| return processNestedSelectors(allSelector.children)
| | ! 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 |
|
| |
|
| -- Обработка GroupSelector
| | local function generateFooter() |
| handleGroupSelector = function(groupSelector)
| | return "|}" |
| if not groupSelector.children then return '' end | |
| local result = ""
| |
| local wrapperStart, wrapperEnd = "", ""
| |
| | |
| -- Проверка для контейнера EntityTableContainerFill
| |
| if groupSelector.weight and groupSelector.weight ~= "default" then
| |
| wrapperStart = string.format('{{LinkСard/Сollapsible|name=Группа предметов %s%%|content=', groupSelector.weight)
| |
| wrapperEnd = "}}"
| |
| elseif groupSelector["!type"] == "GroupSelector" and not groupSelector.weight then
| |
| wrapperStart = '{{LinkСard/Сollapsible|name=Может выпасть лишь один из:|content='
| |
| wrapperEnd = "}}"
| |
| end
| |
| | |
| for _, child in ipairs(groupSelector.children) do
| |
| if child["!type"] == "GroupSelector" then
| |
| result = result .. handleGroupSelector(child)
| |
| elseif child["!type"] == "AllSelector" then
| |
| result = result .. string.format('{{LinkСard/Сollapsible|name=Выпадают только вместе:|content=%s}}', handleAllSelector(child))
| |
| elseif child.id then
| |
| result = result .. formatContent(child)
| |
| else
| |
| result = result .. "<div>Ошибка: отсутствует id у элемента.</div>"
| |
| end
| |
| end
| |
| | |
| return wrapperStart .. result .. wrapperEnd
| |
| end | | end |
|
| |
|
| -- Обработка NestedSelector
| | function p.table(frame) |
| handleNestedSelector = function(nestedSelector, wrapped, visited)
| | local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data") |
| visited = visited or {}
| | local rows = {} |
| if not nestedSelector.tableId then return '' end
| |
|
| |
|
| local result = "" | | for _, seed in ipairs(data) do |
| local classesRolls, classesProb
| | local prodId = seed.productPrototypes[1] |
| | local seedId = seed.packetPrototype |
| | local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId) |
|
| |
|
| if wrapped then
| | local anchor = string.format('{{anchor|%s}}', seedName) |
| if nestedSelector.rolls and nestedSelector.rolls.range then | | local fruitImg = string.format( |
| local rollsResult = processRolls(nestedSelector.rolls)
| | '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}', |
| if rollsResult and #rollsResult > 0 then | | prodId, seedName |
| classesRolls = ', максимум может выпасть: ' .. rollsResult
| | ) |
| end | | local seedImg = string.format( |
| end | | '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}', |
| if nestedSelector.prob then | | seedId, seedName |
| classesProb = string.format(" <div>%s%%</div>", nestedSelector.prob * 100 >= 1 and math.floor(nestedSelector.prob * 100) or nestedSelector.prob * 100) | | ) |
| end | | local plantImg = string.format( |
| end
| | '{{Предмет|%s-harvest|size=64px|l=|link=%s}}', |
| | seedId, seedName |
| | ) |
|
| |
|
| if wrapped and (classesRolls or classesProb) then | | local colGrowth = formatCharacteristics(seed) |
| result = result .. string.format('{{LinkСard/Сollapsible|name=Группа предметов%s%s|content=', classesRolls or "", classesProb or "") | | local colConditions = formatConditions(seed) |
| end
| | local colHarvest = formatHarvestType(seed) |
| | | local colChemicals = formatChemicals(seed) |
| result = result .. getTableOutput(nestedSelector.tableId, visited)
| | local colMutations = formatMutations(seed, data) |
|
| |
|
| if wrapped and (classesRolls or classesProb) then
| | local row = frame:preprocess(string.format( |
| result = result .. "}}" | | [[|- |
| | ! %s |
| | ! %s |
| | ! %s |
| | | %s |
| | | %s |
| | | %s |
| | | %s |
| | | %s ]], |
| | fruitImg, seedImg, plantImg, |
| | colGrowth, colConditions, colHarvest, |
| | colChemicals, colMutations |
| | )) |
| | table.insert(rows, row) |
| end | | end |
|
| |
|
| return result | | return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter() |
| end
| |
| | |
| -- Формирование списка химии
| |
| getChemOutput = function(itemData, id)
| |
| local item = findDataById(itemData, id)
| |
| if not item or not item.SolutionContainerManager or not item.SolutionContainerManager.solutions then return '' end
| |
| | |
| local result = ""
| |
| for _, solution in pairs(item.SolutionContainerManager.solutions) do
| |
| for _, reagent in ipairs(solution.reagents) do
| |
| result = result .. string.format('<li>[[Химия#chem_%s|%s]] (%d ед.)</li>', reagent.ReagentId, reagent.ReagentId, reagent.Quantity)
| |
| end
| |
| end
| |
| return string.format('<ul class="1">%s</ul>', result)
| |
| end | | end |
|
| |
|
| -- Основная функция модуля
| |
| function p.main(frame) | | function p.main(frame) |
| local mode = frame.args[1] | | local args = frame.args |
| local id = frame.args[2] | | local id = args[1] |
| | | local mode = mw.text.trim(args[2] or ""):lower() |
| if not id then return 'Не указан ID.' end
| | local seed = findSeedById(id, seedsData) |
|
| | if not seed then return "" end |
| local itemDataIndex = itemData | |
|
| |
| if not itemData then return 'Не удалось загрузить данные.' end
| |
| | |
| if mode == 'framing' then
| |
| local subMode = frame.args[2]
| |
| local id = frame.args[3]
| |
| | |
| if not id then
| |
| return 'Не указан ID для режима framing.'
| |
| end
| |
| | |
| if subMode == 'chem' then
| |
| return frame:preprocess('{{СollapsibleMenu|' .. getChemOutput(itemDataIndex, id) .. '}}')
| |
| elseif subMode == 'contained' then
| |
| return frame:preprocess('{{СollapsibleMenu|' .. getContainedOutput(itemDataIndex, id) .. '}}')
| |
| else
| |
| return 'Неизвестный подрежим для framing: ' .. subMode
| |
| end
| |
| elseif mode == 'chem' then | |
| return frame:preprocess(getChemOutput(itemDataIndex, id))
| |
| elseif mode == 'contained' then
| |
| return frame:preprocess(getContainedOutput(itemDataIndex, id))
| |
| elseif mode == 'rolls' then | |
| local entity = findDataById(itemDataIndex, id)
| |
| if not entity then return 'ID не найден в данных.' end
| |
| | |
| if entity.EntityTableContainerFill then
| |
| local containers = entity.EntityTableContainerFill.containers
| |
| if containers.entity_storage and containers.entity_storage.rolls then
| |
| return processRolls(containers.entity_storage.rolls)
| |
| end
| |
| end
| |
|
| |
|
| return '' | | 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 'Неизвестный режим: ' .. mode | | return "" |
| end | | end |
| end | | end |
|
| |
|
| return p | | return p |