Модуль:Крафт

Этот модуль является непосредственной реализацией шаблона {{Крафт}}; аргументы, следовательно, принимаются те же, что и у шаблона. В других модулях следует вызывать сам этот модуль.

Аргументы принимаются как напрямую, так и через страницу, в которой модуль используется. Однако аргументы, переданные напрямую, имеют бо́льший приоритет.

Зависимости

См. также

-- Модуль для создания таблиц с рецептами для крафта. local p = {} local slot = require( [[Модуль:Инвентарный слот]] ) local getParts = slot.getParts local prefixes = slot.prefixes -- Сервисная функция local function prefixedLink( name, mod ) local prefix = '' for _, thisPrefix in pairs( prefixes ) do if mw.ustring.find(name, '^' .. thisPrefix .. ' ' ) then prefix = thisPrefix .. ' ' name = mw.ustring.gsub(name, '^' .. prefix, '' ) break end end local page = '' if mod and mod ~= '' then local ucfirstName = mw.ustring.upper(mw.ustring.sub(name, 1, 1)) .. mw.ustring.sub(name, 2) return prefix .. '[[' .. mod .. '/' .. ucfirstName .. '|' .. name .. ']]' else return prefix .. '[[' .. name .. ']]' end end -- Строительство таблицы function p.table( f ) local args = f if f == mw.getCurrentFrame() then args = require( 'Модуль:ProcessArgs' ).merge() else f = mw.getCurrentFrame() end -- Начинать таблицу при необходимости local multirow = f:callParserFunction( '#dplvar', 'multirow' ) if multirow ~= '1' then multirow = nil end local head = args["глава"] or '0' if tonumber(head) then head = tonumber(head) else error("Параметр «глава» не является числом.") end if multirow then head = 0 elseif head ~= 0 then multirow = 1 f:callParserFunction( '#dplvar:set', 'multirow', '1' ) else head = 1 end -- Заканчивать таблицу при необходимости local foot = args["подвал"] or '' if multirow then if foot ~= '' then multirow = nil f:callParserFunction( '#dplvar:set', 'multirow', '0' ) end else foot = 1 end local header = '' if head ~= 0 then local name = '' local description = '' if args["показатьимя"] == '1' or multirow and args["показатьимя"] ~= '0' then name = '!! Результат' f:callParserFunction( '#dplvar:set', 'resultname', '1' ) end if args["показатьописание"] == '1' then description = ' !! class="unsortable" | Описание' f:callParserFunction( '#dplvar:set', 'craftingdescription', '1' ) end local class = args["класс"] or '' local recipeClass = '' if multirow then class = 'sortable collapsible ' .. class recipeClass = 'class="unsortable" |' end local table_head if head >= 2 then table_head = '|-' else table_head = ' {| style="text-align:center" class="wikitable ' .. class .. '" data-description="Рецепты крафта"' end if head ~= 3 then if args["Мод"] then header = table.concat( { table_head, '! ' .. 'Ингредиенты !! ' .. recipeClass .. ' Процесс' .. name .. description, '|-' }, '\n' ) else header = table.concat( { table_head, '! ' .. 'Ингредиенты !! ' .. recipeClass .. ' Рецепты [[крафт]]а' .. name .. description, '|-' }, '\n' ) end end end -- Ячейка с названием local nameCell if f:callParserFunction( '#dplvar', 'resultname' ) == '1' then if args["название"] or '' ~= '' then nameCell = args["название"] else local names = {} local links = {} for v in mw.text.gsplit( args["Выход"] or '', '%s*;%s*' ) do parts = getParts( v, args["Мод"] ) parts.mod = parts.mod or '' if not names[parts.mod .. ':' .. parts.name] then table.insert( links, prefixedLink( parts.name, parts.mod ) ) names[parts.mod .. ':' .. parts.name] = 1 end end nameCell = table.concat( links, '&nbsp;или<br>' ) end end if nameCell and args["запланированное"] then nameCell = nameCell .. '<br>([[' .. args["запланированное"] .. ']])' end -- Создать список ингредиентов local ingredients = {} local ingredientKeys = {} local animatedIngredients = {} local animatedKeys = {} for k, v in pairs( args ) do v = mw.text.trim( v ) if v ~= '' and mw.ustring.find(tostring( k ), '^%u?%d%d?$' ) then if mw.ustring.find(v, ';' ) then table.insert( animatedKeys, v ) else local parts = getParts( v, args["Мод"] ) parts.mod = parts.mod or '' local fullName = parts.mod .. ':' .. parts.name if not ingredients[fullName] then table.insert( ingredientKeys, fullName ) ingredients[fullName] = { mod = parts.mod, name = parts.name } end end end end for k, v in ipairs( animatedKeys ) do local frames = mw.text.split( v, '%s*;%s*' ) local length = #frames for k2, v2 in ipairs( frames ) do local parts = getParts( v2, args["Мод"] ) parts.mod = parts.mod or '' local fullName = parts.mod .. ':' .. parts.name if v2 ~= '' and not ingredients[fullName] and not animatedIngredients[fullName] then table.insert( ingredientKeys, fullName ) animatedIngredients[fullName] = { mod = parts.mod, name = parts.name, final = k2 == length } end end end -- Ячейка с ингредиентами local ingredientsCell if args["ингредиенты"] or '' ~= '' then ingredientsCell = args["ингредиенты"] else ingredientsCell = {} for k, v in ipairs( ingredientKeys ) do local separator = '&nbsp;+' if k == #ingredientKeys then separator = '' elseif animatedIngredients[v] and not animatedIngredients[v].final then separator = '&nbsp;или' end local mod = ( ingredients[v] or animatedIngredients[v] ).mod local name = ( ingredients[v] or animatedIngredients[v] ).name table.insert( ingredientsCell, prefixedLink( name, mod ) .. separator ) end ingredientsCell = table.concat( ingredientsCell, '<br>' ) end -- Автоматическое расположение ингредиентов в бесформенном рецепте local newArgs = {} if args[1] then newArgs["бесформенный"] = 1 if args[7] then newArgs.A1 = args[1] newArgs.B1 = args[2] newArgs.C1 = args[3] newArgs.A2 = args[4] newArgs.B2 = args[5] newArgs.C2 = args[6] if args[8] then -- ◼◼◼ ◼◼◼ -- ◼◼◼ OR ◼◼◼ -- ◼◼◼ ◼◼◻ newArgs.A3 = args[7] newArgs.B3 = args[8] newArgs.C3 = args[9] if args[9] then local identical = true for i = 1, 8 do if args[i] ~= args[i + 1] then identical = false end end if identical then newArgs["бесформенный"] = nil end end else -- ◼◼◼ -- ◼◼◼ -- ◻◼◻ newArgs.B3 = args[7] end elseif args[2] then newArgs.A2 = args[1] newArgs.B2 = args[2] if args[5] then -- ◻◻◻ ◻◻◻ -- ◼◼◼ OR ◼◼◼ -- ◼◼◼ ◼◼◻ newArgs.C2 = args[3] newArgs.A3 = args[4] newArgs.B3 = args[5] newArgs.C3 = args[6] elseif args[4] then -- ◻◻◻ -- ◼◼◻ -- ◼◼◻ newArgs.A3 = args[3] newArgs.B3 = args[4] else -- ◻◻◻ ◻◻◻ -- ◼◼◻ OR ◼◼◻ -- ◻◼◻ ◻◻◻ newArgs.B3 = args[3] end else -- ◻◻◻ -- ◻◼◻ -- ◻◻◻ newArgs.B2 = args[1] newArgs["бесформенный"] = nil end else newArgs.A1 = args.A1 newArgs.B1 = args.B1 newArgs.C1 = args.C1 newArgs.A2 = args.A2 newArgs.B2 = args.B2 newArgs.C2 = args.C2 newArgs.A3 = args.A3 newArgs.B3 = args.B3 newArgs.C3 = args.C3 newArgs["фиксированный"] = args["фиксированный"] newArgs["нефиксировано"] = args["нефиксировано"] end -- Остальные аргументы newArgs["Мод"] = args["Мод"] newArgs["Выход"] = args["Выход"] newArgs["ВНазв"] = args["ВНазв"] newArgs["ВСсылка"] = args["ВСсылка"] -- Ячейка с рецептом local recipeCell = require( 'Модуль:Интерфейс' ).craftingTable( newArgs ) local row = { '| ' .. ingredientsCell, 'style="padding:1px" |\n' .. recipeCell } if nameCell then table.insert( row, 3, '<b>' .. nameCell .. '</b>' ) end if f:callParserFunction( '#dplvar', 'craftingdescription' ) == '1' then table.insert( row, args["описание"] or '' ) end row = table.concat( row, '\n|' ) local footer = '' if foot ~= '' then footer = '|}' f:callParserFunction( '#dplvar:set', 'resultname', '0', 'craftingdescription', '0' ) end -- Создание различных категорий для DPL local title = mw.title.getCurrentTitle() local categories = '' local makecat = true if args["некат"] == '1' then makecat = false end if title.namespace ~= 0 then makecat = false end if title.isSubpage then if title.subpageText ~= "крафт" then makecat = false end else if mw.title.new(title.fullText ..'/крафт').exists then makecat = false end end if makecat then categories = {} if args["запланированное"] then table.insert( categories, '[[Категория:Запланированные материалы]]' ) end if args["тип"] then table.insert( categories, '[[Категория:Рецепты/' .. args["тип"] .. ']]' ) end if args["игнорировать"] ~= '1' then local dyes = { 'Оранжевый краситель', 'Сиреневый краситель', 'Светло-синий краситель', 'Жёлтый краситель', 'Лаймовый краситель', 'Розовый краситель', 'Серый краситель', 'Светло-серый краситель', 'Бирюзовый краситель', 'Фиолетовый краситель', 'Лазурит', 'Какао-бобы', 'Кактусовая зелень', 'Красный краситель', 'Чернильный мешок' } -- Названия в следующем списке должны писаться ОБЯЗАТЕЛЬНО со строчной буквы, так как встречаются в середине названия: local variants = { 'древесина', 'доски', 'окрашенное стекло', 'окрашенная стеклянная панель', 'шерсть', 'песчаник', 'ступени', 'плита', 'нажимная пластина', 'звёздочка', 'каменный кирпич', 'андезит', 'диорит', 'гранит', 'щит', 'ящик шалкера' } for k, v in ipairs( ingredientKeys ) do v = mw.ustring.sub(v, 2 ) if not mw.ustring.find(v, ':' ) then if v == 'Любой краситель' or v == 'Любой цветной краситель' then if v == 'Любой краситель' then table.insert( dyes, 1, 'Костная мука' ) end for _, dye in ipairs( dyes ) do -- В оригинале название категории имеет формат «Recipe using <предмет>». Прямо переводится -- эта конструкция как «Рецепт, использующий <предмет>». При этом название предмета должно -- было быть в винительном падеже, но на данный момент быстро склонять название предметов -- в именительном падеже с помощью модулей не представляется возможным. Поэтому в качестве -- перевода используется близкая по смыслу конструкция, не требующая склонения. table.insert( categories, '[[Категория:' .. dye .. ' как ингредиент для крафта]]' ) end else if v == 'Липкий поршень' then v = 'Поршень' elseif v == 'Любой гриб' or v == 'Красный гриб' or v == 'Коричневый гриб' then v = 'Гриб' elseif v == 'Красный песок' then v = 'Песок' elseif v == 'Древесный уголь' then v = 'Уголь' elseif mw.ustring.find(v, 'красный песчаник$' ) then v = 'Песчаник' elseif mw.ustring.find(v, '^Флаг ') or mw.ustring.find(v, ' флаг$') then v = 'Флаг' elseif v == 'Кварцевый пилон' or v == 'Резной кварцевый блок' then v = 'Кварцевый блок' else -- Объединить категории вариантов, описываемых на единой странице for _, variant in pairs( variants ) do if mw.ustring.find(v, ' ' .. variant .. '$' ) then v = variant break end end -- Убрать приставки for _, prefix in pairs( prefixes ) do if mw.ustring.find(v, '^' .. prefix .. ' ' ) then v = mw.ustring.gsub(v, '^' .. prefix .. ' ', '' ) break end end end table.insert( categories, '[[Категория:' .. v .. ' как ингредиент для крафта]]' ) end end end end categories = table.concat( categories, '' ) end return header .. '\n' .. row .. '\n|-\n' .. footer .. categories end return p 
В данной статье используются материалы из статьи «Модуль:Крафт» с вики-сайта Minecraft Wiki, расположенного на Фэндоме, и они распространяются согласно лицензии Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Авторы статьи.