Модуль:Мир Chatmon

Материал из Chatmon Wiki

Для документации этого модуля может быть создана страница Модуль:Мир Chatmon/doc

local data = mw.loadData('Module:Мир Chatmon/данные')
local export = {}

local function link(target, label)
    return '[[' .. target .. (label and label ~= target and '|' .. label or '') .. ']]'
end

local function tableText(columns, rows, simple)
    if not rows[1] then return '' end
    local out = {simple and '{| class="wikitable"' or '{| class="wikitable sortable"'}
    for _, label in ipairs(columns) do
        out[#out + 1] = '! scope="col" | ' .. label
    end
    for _, row in ipairs(rows) do
        out[#out + 1] = '|-'
        for _, cell in ipairs(row) do
            out[#out + 1] = '| ' .. cell
        end
    end
    out[#out + 1] = '|}'
    return table.concat(out, '\n')
end

local function spoiler(text)
    if text == '' then return '' end
    return '{{Сюжетный блок|начало}}\n\n' .. text .. '\n\n{{Сюжетный блок|конец}}'
end

local function place(linkId)
    local location = data.places[linkId]
    return link(data.regions[location[1]]), link(location[3], location[4])
end

local function localPlace(key)
    local location = data.places[key]
    return location[3]:match('#loc%-') and link('#loc-' .. key, location[5]) or location[5]
end

local function findLabel(row)
    if row[5] then return 'Сюжетная, один раз' end
    return row[4] and 'Один раз' or 'Повторяемая'
end

function export.placeFinds(frame)
    local group = assert(data.findGroups[frame.args[1]], 'Неизвестная локация')
    local hidden = frame.args[2] == 'скрытые'
    local headings = {'Предмет', 'Способ', 'Сколько раз', 'Редкость'}
    if group.areas then headings[5] = 'Где искать' end
    local rows, aggregate = {}, {}
    for _, placeId in ipairs(group.places) do
        for _, record in ipairs(data.finds[placeId]) do
            if record[5] == hidden then
                local code = table.concat({record[1], record[2], record[3], tostring(record[4])}, '/')
                local row = aggregate[code]
                if not row then
                    row = {
                        link(data.items[record[1]]), record[2] == 'surfing' and 'На воде' or 'На земле',
                        findLabel(record), data.rates[record[3]] or '—',
                    }
                    aggregate[code] = row
                    rows[#rows + 1] = row
                end
                if group.areas then
                    local area = localPlace(placeId)
                    row[5] = row[5] and row[5] .. ', ' .. area or area
                end
            end
        end
    end
    return frame:preprocess(tableText(headings, rows, hidden))
end

function export.itemFinds(frame)
    local id = frame.args[1]
    local headings = {'Регион', 'Место', 'Действие', 'Доступность', 'Редкость'}
    local normal, hidden = {}, {}
    for _, index in ipairs(assert(data.itemFinds[id], 'Нет находок для предмета')) do
        local region, location = place(index[1])
        local record = data.finds[index[1]][index[2]]
        local rows = record[5] and hidden or normal
        rows[#rows + 1] = {
            region, location, record[2] == 'surfing' and 'При заплыве' or 'При обходе',
            findLabel(record), data.rates[record[3]] or '—',
        }
    end
    return frame:preprocess(tableText(headings, normal) .. '\n\n' .. spoiler(tableText(headings, hidden)))
end

local function price(amount, currency)
    local units = currency == 'tokens' and {'жетон', 'жетона', 'жетонов'} or {'кредит', 'кредита', 'кредитов'}
    local final = amount % 10
    local ending = amount % 100
    local word = ending >= 11 and ending <= 14 and units[3] or
        (final == 1 and units[1] or (final >= 2 and final <= 4 and units[2] or units[3]))
    local number = tostring(amount)
    while true do
        local grouped, changed = number:gsub('^(%-?%d+)(%d%d%d)', '%1&nbsp;%2', 1)
        number = grouped
        if changed == 0 then break end
    end
    return 'data-sort-value="' .. amount .. '" | ' .. number .. ' ' .. word
end

function export.shop(frame)
    local shop = assert(data.shops[frame.args[1]], 'Неизвестный магазин')
    local rows = {}
    for _, good in ipairs(shop.goods) do
        rows[#rows + 1] = {link(data.items[good[1]]), price(good[2], shop.currency), good[3]}
    end
    return frame:preprocess(tableText({'Товар', 'Цена', 'Доступность'}, rows))
end

function export.itemShops(frame)
    local rows = {}
    for _, index in ipairs(assert(data.itemShops[frame.args[1]], 'Нет магазинов для предмета')) do
        local region, location = place(index[1])
        local shop = data.shops[index[1]]
        local good = shop.goods[index[2]]
        rows[#rows + 1] = {region, location, price(good[2], shop.currency), good[3]}
    end
    return frame:preprocess(tableText({'Регион', 'Место', 'Цена покупки', 'Условие'}, rows))
end

function export.gifts(frame)
    local group = assert(data.gifts[frame.args[1]], 'Нет подарков для предмета')
    local headings = {'Регион', 'Место', 'Кто выдаёт', 'Количество', 'Условие'}
    return frame:preprocess(tableText(headings, group.normal) .. '\n\n' .. spoiler(tableText(headings, group.hidden)))
end

local function evolution(frame, index, columns, simple)
    local key = frame.args[1]
    local rows = {}
    for _, number in ipairs(assert(index[key], 'Нет данных об эволюции')) do
        local record = data.evolutions[number]
        local from, to = data.pokemon[record[1]], data.pokemon[record[2]]
        rows[#rows + 1] = {key == record[1] and from or link(from), key == record[2] and to or link(to), record[3]}
    end
    return frame:preprocess(tableText(columns, rows, simple))
end

function export.pokemonEvolution(frame)
    return evolution(frame, data.pokemonEvolutions, {'Из', 'В', 'Условие'}, true)
end

function export.itemEvolution(frame)
    return evolution(frame, data.itemEvolutions, {'Покемон', 'Эволюция', 'Условие'})
end

function export.pvp(frame)
    local values = assert(data.pvp[frame.args[1]], 'Неизвестная локация')
    local note = 'Игра проверяет этот шанс, когда рядом есть возможный соперник. Подробнее о подборе и ограничениях на странице [[PvP#Случайная встреча|PvP]].'
    local function percent(value)
        return (string.format('%g', value):gsub('%.', ',')) .. '%'
    end
    if type(values) == 'number' then
        return frame:preprocess("Базовый шанс в этой локации — '''" .. percent(values) .. "'''. " .. note)
    end
    local rows = {}
    for _, record in ipairs(values) do
        rows[#rows + 1] = {record[1], percent(record[2])}
    end
    return frame:preprocess(tableText({'Участок', 'Базовый шанс'}, rows, true) .. '\n\n' .. note)
end

return export