|
|
| (не показано 125 промежуточных версий этого же участника) |
| Строка 1: |
Строка 1: |
| local p = {} | | local p = {} |
|
| |
|
| ---------------------------------------------------------------------
| | -- Загрузка данных |
| -- Загрузка данных | | local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data") |
| ---------------------------------------------------------------------
| | local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data") |
| local itemData = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data") | |
| local tableData = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data") | |
|
| |
|
| local gearData = mw.loadData("Модуль:IanComradeBot/startingGear.json/data") | | local function kelvinToCelsius(k) |
| local jobData = mw.loadData("Модуль:IanComradeBot/job.json/data")
| | return k - 273.15 |
| local gearRoleLoadout = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
| | end |
| local loadoutData = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
| |
| local loadoutGroupData = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
| |
| | |
| local cargoData = mw.loadData("Модуль:IanComradeBot/prototypes/сargo.json/base")
| |
| | |
| local latheData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
| |
| local recipeData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
| |
| local researchData = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
| |
| local materialData = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
| |
| local chemDataLathe = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
| |
| | |
| local vendingMachinesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines.json/data")
| |
| local inventoriesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/inventories.json/data")
| |
| | |
| ---------------------------------------------------------------------
| |
| -- Вспомогательные функции
| |
| ---------------------------------------------------------------------
| |
|
| |
|
| -- Обобщённый рекурсивный поиск по полю key с условием predicate
| | local function findSeedById(id, data) |
| local function searchInStructure(struct, key, predicate) | | for _, seed in ipairs(data) do |
| if type(struct) ~= "table" then
| | if seed.id == id then |
| return false
| | return seed |
| end
| |
| if struct[key] and predicate(struct[key]) then
| |
| return true
| |
| end
| |
| for _, v in pairs(struct) do | |
| if type(v) == "table" and searchInStructure(v, key, predicate) then | |
| return true | |
| end | | end |
| end | | end |
| return false | | return nil |
| end | | end |
|
| |
|
| local function searchItemInStructure(struct, targetId) | | local function formatCharacteristics(seed) |
| return searchInStructure(struct, "id", function(val) return val == targetId end)
| | 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 | | end |
|
| |
|
| local function searchTableIdInStructure(struct, tableIds) | | local function formatConditions(seed) |
| return searchInStructure(struct, "tableId", function(val) | | local parts = { |
| for _, tid in ipairs(tableIds) do | | ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5), |
| if val == tid then return true end
| | ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75), |
| end | | ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)), |
| return false
| | } |
| end) | | return table.concat(parts, '<br>') |
| end | | end |
|
| |
|
| -- Формирование ссылки для сущности (используется в reverseContained, reverseLathe, reverseVending)
| | local function formatHarvestType(seed) |
| local function createEntityLink(entityId) | | return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-" |
| local nameCode = "{{#invoke:Entity Lookup|getname|" .. entityId .. "}}" | |
| return "[[" .. nameCode .. "|" .. nameCode .. "]]"
| |
| end | | end |
| | | local function formatHarvestType(seed) |
| -- Формирование ссылки для таблицы грузов (reverseCargo)
| | local harvestRepeat = seed.harvestRepeat |
| local function createCargoLink(storage) | | if harvestRepeat == "Repeat" then |
| local nameCode = "{{#invoke:Entity Lookup|getname|" .. storage .. "}}" | | return "[[Гидропоника#Тип урожая|Многолетнее]]" |
| return "[[Таблица грузов#" .. nameCode .. "|" .. nameCode .. "]]"
| | elseif harvestRepeat == "SelfHarvest" then |
| end
| | return "[[Гидропоника#Тип урожая|Самосбор]]" |
| | | else |
| -- Формирование ссылки для роли/джоба (reverseEquipment)
| | return "[[Гидропоника#Тип урожая|Однолетнее]]" |
| local function createJobLink(jobId)
| |
| local translation = "{{#invoke:Ftl|main|translation|" .. jobId .. "}}" | |
| return "[[" .. translation .. "|{{ucfirst:" .. translation .. "}}]]"
| |
| end
| |
| | |
| ---------------------------------------------------------------------
| |
| -- Логика поиска
| |
| ---------------------------------------------------------------------
| |
| | |
| local function findRelatedTables(initialList)
| |
| local results = {}
| |
| local function recursiveSearch(tblId) | |
| if results[tblId] then | |
| return
| |
| end
| |
| results[tblId] = true
| |
| for id, entry in pairs(tableData) do
| |
| if type(entry) == "table" then
| |
| for _, value in pairs(entry) do
| |
| if type(value) == "table" and value.tableId == tblId then
| |
| recursiveSearch(id)
| |
| end
| |
| end
| |
| end
| |
| end
| |
| end
| |
| for _, tblId in ipairs(initialList) do
| |
| recursiveSearch(tblId)
| |
| end
| |
| local res = {}
| |
| for id in pairs(results) do
| |
| table.insert(res, id)
| |
| end | | end |
| return res
| |
| end | | end |
|
| |
|
| local function findMatchingStorages(targetId) | | local function formatChemicals(seed) |
| local initialTables = {} | | if not seed.chemicals then return "-" end |
| for key, tblEntry in pairs(tableData) do | | local list = {} |
| if type(tblEntry) == "table" and searchItemInStructure(tblEntry, targetId) then | | for chemId, vals in pairs(seed.chemicals) do |
| local tableId = tblEntry.id or key
| | local entry = chemData[chemId] |
| table.insert(initialTables, tableId)
| | local chemName = entry and entry.name or chemId |
| end
| | table.insert(list, string.format( |
| end
| | "<li>[[Химия#chem_%s|%s]] (мин: %s, макс: %s, дел: %s)</li>", |
| | | chemId, chemName, vals.Min or 0, vals.Max or 0, vals.PotencyDivisor or 1 |
| local allRelatedTables = (#initialTables > 0) and findRelatedTables(initialTables) or {}
| | )) |
| | |
| local matchingStorages = {}
| |
| for storageKey, storage in pairs(itemData) do
| |
| if type(storage) == "table" then
| |
| local found = false | |
| if storage.EntityTableContainerFill
| |
| and storage.EntityTableContainerFill.containers then
| |
| if searchTableIdInStructure(storage.EntityTableContainerFill.containers, allRelatedTables) then
| |
| found = true
| |
| end
| |
| end
| |
| if searchItemInStructure(storage, targetId) then
| |
| found = true
| |
| end
| |
| if found then
| |
| local actualId = storage.id or storageKey
| |
| table.insert(matchingStorages, actualId)
| |
| end
| |
| end | |
| end | | end |
| | | return "<ul>" .. table.concat(list) .. "</ul>" |
| return matchingStorages | |
| end | | end |
|
| |
|
| ---------------------------------------------------------------------
| | local function formatMutations(seed, data) |
| -- Функции обратного поиска
| | if not seed.mutationPrototypes then return "-" end |
| ---------------------------------------------------------------------
| | local list = {} |
| | | for _, mu in ipairs(seed.mutationPrototypes) do |
| function p.reverseContained(frame) | | local target = findSeedById(mu, data) |
| local targetId = frame.args[2]
| | if target and target.productPrototypes then |
| if not targetId or targetId == "" then | | for _, prod in ipairs(target.productPrototypes) do |
| return "Ошибка: не указан id предмета для обратного поиска."
| | table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod)) |
| end
| |
| | |
| local matchingStorages = findMatchingStorages(targetId) | |
| local filteredStorages = {}
| |
| for _, sid in ipairs(matchingStorages) do | |
| local skip = false | |
| for _, cargo in pairs(cargoData) do | |
| if type(cargo) == "table" and cargo.product == sid then
| |
| skip = true
| |
| break
| |
| end | | end |
| end
| |
| if not skip then
| |
| table.insert(filteredStorages, sid)
| |
| end | | end |
| end | | end |
| | | return "<ul>" .. table.concat(list) .. "</ul>" |
| if #filteredStorages == 0 then | |
| return ""
| |
| end
| |
| | |
| local links = {}
| |
| for _, storage in ipairs(filteredStorages) do
| |
| table.insert(links, createEntityLink(storage))
| |
| end
| |
| | |
| return "Находится в хранилище: " .. table.concat(links, ", ")
| |
| end | | end |
|
| |
|
| function p.reverseEquipment(frame) | | local function generateHeader() |
| local targetId = frame.args[2] | | return [[ |
| local slotFilter = frame.args[3]
| | {| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;" |
| if not targetId or targetId == "" then
| | ! rowspan="2" style="width:10%;" | Плод |
| return "Ошибка: не указан id оборудования для обратного поиска."
| | ! rowspan="2" class="unsortable" style="width:5%;" | Семена |
| end
| | ! rowspan="2" class="unsortable" style="width:5%;" | Растение |
| | | ! colspan="3" class="unsortable" style="width:30%;" id="no-highlight" | Характеристики |
| local results = {}
| | ! rowspan="2" class="unsortable" style="width:30%;" | Содержит вещества |
| | | ! rowspan="2" style="width:20%;" | Мутации |
| -- Обработка startingGear (gearData)
| | |- |
| for _, gear in pairs(gearData) do
| | ! style="width:10%;" class="unsortable" | Рост |
| local currentGearId = gear.id or "Unknown"
| | ! style="width:10%;" class="unsortable" | Условия |
| if gear.equipment then
| | ! style="width:5%;" class="unsortable" | Тип сбора |
| for slot, equipId in pairs(gear.equipment) do
| | ]] |
| if equipId == targetId and (not slotFilter or slot == slotFilter) then
| |
| local foundJob = nil
| |
| for jobId, job in pairs(jobData) do
| |
| if job.startingGear == currentGearId then
| |
| foundJob = jobId
| |
| break
| |
| end
| |
| end
| |
| if foundJob then
| |
| table.insert(results, createJobLink(foundJob))
| |
| end
| |
| end
| |
| end
| |
| end
| |
| end
| |
| | |
| -- Обработка loadout (loadoutData)
| |
| for _, loadout in pairs(loadoutData) do
| |
| if loadout.equipment then
| |
| for slot, equipId in pairs(loadout.equipment) do
| |
| if equipId == targetId and (not slotFilter or slot == slotFilter) then
| |
| local foundGroupId = nil
| |
| for _, group in pairs(loadoutGroupData) do
| |
| if group.loadouts and type(group.loadouts) == "table" then
| |
| for _, lId in ipairs(group.loadouts) do
| |
| if lId == loadout.id then
| |
| foundGroupId = group.id
| |
| break
| |
| end
| |
| end
| |
| end
| |
| if foundGroupId then break end
| |
| end
| |
| local foundJob = nil
| |
| if foundGroupId then
| |
| for _, role in pairs(gearRoleLoadout) do
| |
| if role.groups then
| |
| for _, g in ipairs(role.groups) do
| |
| if g == foundGroupId then
| |
| foundJob = role.id
| |
| break
| |
| end
| |
| end
| |
| end
| |
| if foundJob then break end
| |
| end
| |
| end
| |
| if foundJob then
| |
| table.insert(results, createJobLink(foundJob))
| |
| end
| |
| end
| |
| end
| |
| end
| |
| end
| |
| | |
| if #results == 0 then
| |
| return "Оборудование с id " .. targetId .. " не найдено в наборах экипировки."
| |
| end
| |
| | |
| return "Начальная экипировка роли: " .. table.concat(results, ", ")
| |
| end | | end |
|
| |
|
| function p.reverseCargo(frame) | | local function generateFooter() |
| local searchValue = frame.args[2] | | return "|}" |
| if not searchValue or searchValue == "" then
| |
| return "Ошибка: не указано значение для поиска в режиме cargo."
| |
| end
| |
| | |
| -- Сначала ищем прямые совпадения по product
| |
| local directCargo = {}
| |
| for _, entry in ipairs(cargoData) do
| |
| if entry.product == searchValue then
| |
| table.insert(directCargo, entry.id)
| |
| end
| |
| end
| |
| | |
| if #directCargo > 0 then
| |
| return "Найденные записи cargo: " .. table.concat(directCargo, ", ")
| |
| end
| |
| | |
| -- Если прямых совпадений нет, выполняем обратный поиск среди хранилищ
| |
| local matchingStorages = findMatchingStorages(searchValue)
| |
| local cargoStorages = {}
| |
| for _, sid in ipairs(matchingStorages) do
| |
| for _, cargo in pairs(cargoData) do
| |
| if type(cargo) == "table" and cargo.product == sid then
| |
| table.insert(cargoStorages, sid)
| |
| break
| |
| end
| |
| end
| |
| end
| |
| | |
| if #cargoStorages == 0 then
| |
| return ""
| |
| end
| |
| | |
| local links = {}
| |
| for _, storage in ipairs(cargoStorages) do
| |
| table.insert(links, createCargoLink(storage))
| |
| end
| |
| return "Заказ груза: " .. table.concat(links, ", ")
| |
| end | | end |
|
| |
|
| local function getRecipeById(recipeId)
| | function p.table(frame) |
| for _, recipe in ipairs(recipeData) do | | local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data") |
| if recipe.id == recipeId then
| | local rows = {} |
| return recipe
| |
| end
| |
| end
| |
| return nil
| |
| end
| |
|
| |
|
| function p.reverseLathe(frame)
| | for _, seed in ipairs(data) do |
| local targetResult = frame.args[2]
| | local prodId = seed.productPrototypes[1] |
| if not targetResult or targetResult == "" then
| | local seedId = seed.packetPrototype |
| return "Ошибка: не указан результат рецепта для обратного поиска." | | local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId) |
| end
| |
|
| |
|
| local matchingLathes = {}
| | local anchor = string.format('{{anchor|%s}}', seedName) |
| local function checkRecipes(recipeIds)
| | local fruitImg = string.format( |
| for _, recipeId in ipairs(recipeIds or {}) do | | '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}', |
| local recipe = getRecipeById(recipeId)
| | prodId, seedName |
| if recipe and recipe.result == targetResult then | | ) |
| return true
| | local seedImg = string.format( |
| end | | '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}', |
| end | | seedId, seedName |
| return false
| | ) |
| end
| | local plantImg = string.format( |
| | | '{{Предмет|%s-harvest|size=64px|l=|link=%s}}', |
| for _, lathe in ipairs(latheData) do
| | seedId, seedName |
| local found = false | | ) |
| if lathe.Lathe then
| |
| if checkRecipes(lathe.Lathe.staticRecipes) or checkRecipes(lathe.Lathe.dynamicRecipes) then | |
| found = true
| |
| end | |
| end | |
| if not found and lathe.EmagLatheRecipes then | |
| if checkRecipes(lathe.EmagLatheRecipes.emagStaticRecipes) or checkRecipes(lathe.EmagLatheRecipes.emagDynamicRecipes) then | |
| found = true
| |
| end | |
| end
| |
| if found and lathe.id then | |
| table.insert(matchingLathes, lathe.id)
| |
| end
| |
| end
| |
|
| |
|
| if #matchingLathes == 0 then | | local colGrowth = formatCharacteristics(seed) |
| return "" | | local colConditions = formatConditions(seed) |
| end
| | local colHarvest = formatHarvestType(seed) |
| | local colChemicals = formatChemicals(seed) |
| | local colMutations = formatMutations(seed, data) |
|
| |
|
| local links = {}
| | local row = frame:preprocess(string.format( |
| for _, latheId in ipairs(matchingLathes) do
| | [[|- |
| table.insert(links, createEntityLink(latheId)) | | ! %s |
| | ! %s |
| | ! %s |
| | | %s |
| | | %s |
| | | %s |
| | | %s |
| | | %s ]], |
| | fruitImg, seedImg, plantImg, |
| | colGrowth, colConditions, colHarvest, |
| | colChemicals, colMutations |
| | )) |
| | table.insert(rows, row) |
| end | | end |
|
| |
|
| return "Может быть напечатано на станке: " .. table.concat(links, ", ") | | return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter() |
| end | | end |
|
| |
|
| function p.reverseVending(frame)
| |
| local invMode = frame.args[2] or "" -- режим: "inventory", "contraband", "emag" или пустая строка для всех
| |
| local targetId = frame.args[3]
| |
| if not targetId or targetId == "" then
| |
| return "Ошибка: не указан id предмета для обратного поиска в торговых автоматах."
| |
| end
| |
|
| |
| -- Определяем соответствующие ключи для поиска в инвентарях
| |
| local inventoryTypes = {
| |
| inventory = "startingInventory",
| |
| contraband = "contrabandInventory",
| |
| emag = "emaggedInventory"
| |
| }
| |
|
| |
| local matchingInventoryIds = {}
| |
| for _, inventory in pairs(inventoriesData) do
| |
| if inventory.id then
| |
| local found = false
| |
| if invMode ~= "" then
| |
| local key = inventoryTypes[invMode]
| |
| if key and inventory[key] and type(inventory[key]) == "table" and inventory[key][targetId] then
| |
| found = true
| |
| end
| |
| else
| |
| for _, key in pairs(inventoryTypes) do
| |
| if inventory[key] and type(inventory[key]) == "table" and inventory[key][targetId] then
| |
| found = true
| |
| break
| |
| end
| |
| end
| |
| end
| |
| if found then
| |
| table.insert(matchingInventoryIds, inventory.id)
| |
| end
| |
| end
| |
| end
| |
|
| |
| if #matchingInventoryIds == 0 then
| |
| return ""
| |
| end
| |
|
| |
| local matchingVendingMachines = {}
| |
| for _, vm in pairs(vendingMachinesData) do
| |
| if vm.VendingMachine and vm.VendingMachine.pack then
| |
| for _, invId in ipairs(matchingInventoryIds) do
| |
| if vm.VendingMachine.pack == invId then
| |
| if vm.id then
| |
| table.insert(matchingVendingMachines, vm.id)
| |
| end
| |
| break
| |
| end
| |
| end
| |
| end
| |
| end
| |
|
| |
| if #matchingVendingMachines == 0 then
| |
| return ""
| |
| end
| |
|
| |
| local links = {}
| |
| for _, vmId in ipairs(matchingVendingMachines) do
| |
| table.insert(links, createEntityLink(vmId))
| |
| end
| |
|
| |
| -- Разные текстовые сообщения для каждого режима
| |
| local modeTexts = {
| |
| inventory = "Содержится в торгомате: ",
| |
| contraband = "Содержится в торгомате ([[Взламываемые криптографическим секвенсором предметы|EMAG]]): ",
| |
| emag = "Содержится в торгомате ([[Руководство по взлому|взлом]]): "
| |
| }
| |
| local outputText = modeTexts[invMode] or "Содержится в торгомате: "
| |
| return outputText .. table.concat(links, ", ")
| |
| end
| |
|
| |
| ---------------------------------------------------------------------
| |
| -- Основная функция модуля
| |
| ---------------------------------------------------------------------
| |
| function p.main(frame) | | function p.main(frame) |
| local mode = frame.args[1] | | local args = frame.args |
| if not mode or mode == "" then | | local id = args[1] |
| return "Ошибка: не указан режим обратного поиска. Доступные режимы: reverseContained, reverseEquipment, reverseCargo, reverseLathe, reverseVending."
| | local mode = mw.text.trim(args[2] or ""):lower() |
| end
| | local seed = findSeedById(id, seedsData) |
| | if not seed then return "" end |
|
| |
|
| local modeFunctions = { | | if mode == "growth" then |
| reverseContained = p.reverseContained,
| | return formatCharacteristics(seed) |
| reverseEquipment = p.reverseEquipment, | | elseif mode == "conditions" then |
| reverseCargo = p.reverseCargo,
| | return formatConditions(seed) |
| reverseLathe = p.reverseLathe, | | elseif mode == "harvest" then |
| reverseVending = p.reverseVending, | | return formatHarvestType(seed) |
| } | | elseif mode == "chemicals" then |
| | | return formatChemicals(seed) |
| if modeFunctions[mode] then | | elseif mode == "mutations" then |
| return mw.getCurrentFrame():preprocess(modeFunctions[mode](frame)) | | return formatMutations(seed, seedsData) |
| else | | else |
| return "Неизвестный режим: " .. mode .. ". Доступные режимы: reverseContained, reverseEquipment, reverseCargo, reverseLathe, reverseVending." | | return "" |
| end | | end |
| end | | end |
|
| |
|
| return p | | return p |