Module:Sandbox/LVL: Difference between revisions

Jump to navigation Jump to search
LVL (talk | contribs)
No edit summary
LVL (talk | contribs)
No edit summary
Line 1: Line 1:
local p = {}
local p = {}
local heroes_data = mw.loadJsonData("Data:HeroData.json")
local items_data = mw.loadJsonData("Data:ItemData.json")
local items_data = mw.loadJsonData("Data:ItemData.json")
local lang_module = require('Module:Lang')
local generic_module = require('Module:GenericData')
local util_module = require('Module:Utilities')


-- Helper to find Item Buildup value by name
--With debug_mode on, it outputs unprocessed wikitext
-- Handles both flat numbers and lookup in the ItemData file
--With debug_mode off/unspecified, it processes the wikitext
local function get_item_bb(target_name)
local function process_debug_mode(wikitext, debug_mode)
if target_name == nil then return nil end
if debug_mode == 'true' then
return wikitext
-- Clean input
elseif debug_mode == 'false' or debug_mode == nil then
local clean_name = mw.text.trim(target_name)
return mw.getCurrentFrame():preprocess(wikitext)
else
-- If user input a number directly
return "debug_mode must be 'true' or 'false'"
if tonumber(clean_name) then return tonumber(clean_name) end
end
end


-- Iterate Item Data
--Writes list of items of a certain slot within the min and max soul bounds
for key, item in pairs(items_data) do
-- Each item is wrapped and separated. For example of wrapping/separator, see
if item["Name"] == clean_name then
-- get_item_nav_bulletpoints. 'sep' should not be combined with 'right_wrap',
-- as the trailing separator should also be removed from the string
-- Valve data structure (nested)
-- NEW: filter_mode parameter added. Options: nil/"all", "exclude_street_brawl", "street_brawl_only"
if item["m_mapAbilityProperties"] and item["m_mapAbilityProperties"]["BuildUpPerShot"] then
local function write_wrapped_item_list(slot, min_souls, max_souls, template, sep, filter_mode)
return tonumber(item["m_mapAbilityProperties"]["BuildUpPerShot"]["m_strValue"])
    if slot ~= 'Weapon' and slot ~= 'Armor' and slot ~= 'Tech' then
end
        return 'slot must be Weapon, Armor (Vitality), or Tech (Spirit)'
    end
-- Flat data structure (fallback)
   
if item["BuildUpPerShot"] then
    local min_souls = tonumber(min_souls)
return tonumber(item["BuildUpPerShot"])
    local max_souls = tonumber(max_souls)
end
    if min_souls == nil or max_souls == nil then return 'Min/Max souls must be numerical' end
end
   
end
    -- Normalize filter_mode
return nil
    filter_mode = filter_mode or "all"
   
    -- Retrieve all items that fit the bounds
    local items = {}
    for item_key, item_data in pairs(items_data) do
        -- future proofing; Disabled will be renamed to IsDisabled soon
        local this_cost = tonumber(item_data["Cost"])
        local this_slot = item_data["Slot"]
       
        -- NEW: Filter logic for Street Brawl items
        local is_street_brawl = item_data["StreetBrawl"] == true
        local should_include = true
       
        if filter_mode == "street_brawl_only" and not is_street_brawl then
            should_include = false
        elseif filter_mode == "exclude_street_brawl" and is_street_brawl then
            should_include = false
        end
       
        if should_include and item_data["Name"] ~= nil and item_data["IsDisabled"] == false and this_cost ~= nil and this_slot ~= nil then
            if slot == this_slot and this_cost >= min_souls and this_cost < max_souls then
                local item_name_english = lang_module.get_string(item_key, "en") -- Get the English name
                local lang_code = lang_module.get_lang_code() -- Get the language code from the subpage
                local item_name_local = lang_module.get_string(item_key, lang_code) -- Get the localized name
               
                -- Construct the template based on the type
                local item_template
                if template == "ItemIcon" then
                    if lang_code == "en" then
                        -- For English pages, do not include lang or localized name
                        item_template = "{{ItemIcon|" .. item_name_english .. "}}"
                    else
                        -- For non-English pages, include lang and localized name
                        item_template = "{{ItemIcon|" .. item_name_english .. "|lang=" .. lang_code .. "|" .. item_name_local .. "}}"
                    end
                elseif template == "ItemBox" then
                    if lang_code == "en" then
                        -- For English pages, do not include item_loc or link
                        item_template = "{{ItemBox|item_name=" .. item_name_english .. "}}"
                    else
                        -- For non-English pages, include item_loc and link
                        local link = item_name_english .. "/" .. lang_code -- Add subpage for non-English languages
                        item_template = "{{ItemBox|item_name=" .. item_name_english .. "|item_loc=" .. item_name_local .. "|link=" .. link .. "}}"
                    end
                else
                    return "Invalid template type"
                end
                table.insert(items, item_template)
            end
        end
    end
   
    -- Order list alphabetically
    table.sort(items) -- O(nlogn)
   
    -- Add each item to output
    -- Each item is already wrapped in the template, so no need for additional wrapping
    local ret = table.concat(items, sep)
   
    return ret
end
end


-- Helper to find Hero Data by name or key
-- for [[Template:Item Navbox]]
local function get_hero_data(hero_name)
-- NEW: Added filter parameter support
if hero_name == nil then return nil end
function p.get_item_nav_bulletpoints(slot, min_souls, max_souls, debug_mode, filter_mode)
    -- Handle the case where it's called via #invoke (i.e., from wikitext)
local clean_name = mw.text.trim(hero_name)
    if type(slot) == "table" and slot.args then
        local frame = slot
        slot = frame.args[1]
        min_souls = frame.args[2]
        max_souls = frame.args[3]
        debug_mode = frame.args["debug_mode"]
        filter_mode = frame.args["filter"] -- NEW: grab filter from template args
    end
-- Try direct Key lookup
    local sep = ' &bull; '
if heroes_data[clean_name] then return heroes_data[clean_name] end
-- Try adding "hero_" prefix
    local item_list = write_wrapped_item_list(slot, min_souls, max_souls, "ItemIcon", sep, filter_mode)
local key_lower = "hero_" .. string.lower(clean_name)
if heroes_data[key_lower] then return heroes_data[key_lower] end
-- Search by Name field
    return process_debug_mode(item_list, debug_mode)
for k, v in pairs(heroes_data) do
if v["Name"] == clean_name then return v end
end
return nil
end
end


-- Core calculation logic
-- for [[Template:Infobox ShopItems]]
local function calculate_bps(hero, bb)
-- NEW: Added filter parameter support
if not hero or not hero.Weapon then return 0 end
function p.get_item_nav_cards(slot, min_souls, max_souls, debug_mode, filter_mode)
 
    -- Handle the case where it's called via #invoke (i.e., from wikitext)
local rps = tonumber(hero.Weapon.RoundsPerSecond or 0)
    if type(slot) == "table" and slot.args then
local spin_rps = tonumber(hero.Weapon.RoundsPerSecondAtMaxSpin or 0)
        local frame = slot
        slot = frame.args[1]
        min_souls = frame.args[2]
        max_souls = frame.args[3]
        debug_mode = frame.args["debug_mode"]
        filter_mode = frame.args["filter"] -- NEW: grab filter from template args
    end
    local sep = ' '
    local item_list = write_wrapped_item_list(slot, min_souls, max_souls, "ItemBox", sep, filter_mode)
-- Handle Spin-up logic (McGinnis/Bebop)
    return process_debug_mode(item_list, debug_mode)
-- If they have a max spin speed, use that instead of base RPS
if spin_rps > 0 then rps = spin_rps end
 
if rps == 0 then return 0 end
 
-- Formula: 100 / (BB * (RPS + 1))
return 100 / (bb * (rps + 1))
end
end


--{{#invoke:Buildup|get_bps|HERO_NAME|ITEM_NAME}}
-- for [[Template:Item Navbox]] subgroup rows
--Returns a single float value (rounded to 1 decimal)
function p.write_item_slot_subgroup(frame)
p.get_bps = function(frame)
local slot = frame.args[1]
local hero_name = frame.args[1] or frame.args['hero']
local type = frame.args[2]
local item_name = frame.args[2] or frame.args['item']
local debug_mode = frame.args['debug_mode']
 
local street_brawl_label = frame.args['street_brawl_label'] or "Street Brawl" -- Allow custom label
local hero = get_hero_data(hero_name)
if not hero then return "Hero Not Found" end
if slot == nil then return "'slot' parameter is required" end
 
local bb = get_item_bb(item_name)
-- Define base args
if not bb then return "Item Not Found" end
local template_title = "Navbox subgroup"
 
local template_args = {
local result = calculate_bps(hero, bb)
["groupstyle"] = "background-color:" .. util_module.get_slot_color(slot) .. ";width:10%;min-width:70px;border-radius: 8px 0 0 8px",
return string.format("%.1f", result)
["grouppadding"] = "5px",
end
["listpadding"] = "0 0.25rem",
 
}
--{{#invoke:Buildup|write_buildup_table|ITEM_NAME}}
--Generates a sortable wikitable for all heroes
p.write_buildup_table = function(frame)
local item_name = frame.args[1]
local bb = get_item_bb(item_name)
local soul_style = "font-size: 12px; text-shadow: 1px 1px rgba(0, 0, 0, 0.3);"
if not bb then return "Error: Item '" .. (item_name or "nil") .. "' not found." end
local prices = generic_module.get_item_price_per_tier()
 
local group_index = 1 -- Manual index to handle skipped empty groups
local hero_list = {}
-- Collect valid heroes
for i, souls in ipairs(prices) do
for key, hero in pairs(heroes_data) do
--Determine lower bound for soul
local is_dev = hero["InDevelopment"] == true
min_souls = souls
local is_disabled = hero["IsDisabled"] == true
if not is_dev and not is_disabled and hero["Weapon"] then
--Skip 0 to i1 as no items cost less than 500
local val = calculate_bps(hero, bb)
if min_souls ~= 0 then
-- Determine upper bound
max_souls = prices[i+1]
if max_souls == nil then  
max_souls = min_souls * 10 --essentially have no upper bound
end
-- Generate list for this price tier, EXCLUDING Street Brawl items
local list
if type=='get_item_nav_cards' then
list = p.get_item_nav_cards(slot, min_souls, max_souls, debug_mode, "exclude_street_brawl")
elseif type=='get_item_nav_bulletpoints' then
list = p.get_item_nav_bulletpoints(slot, min_souls, max_souls, debug_mode, "exclude_street_brawl")
else
return "'type' should be get_item_nav_cards or get_item_nav_bulletpoints"
end
if val > 0 then
-- Only add the group if there are items in this tier (prevents empty "$9999" row if all are Street Brawl)
-- Calculate shots needed (Rounding UP is crucial for 19.99% edge cases)
if list and list ~= "" then
local shots = math.ceil(100 / val)
template_args["group" .. group_index] = frame:expandTemplate{title="Souls", args={[1] = min_souls, ["Shadow"] = soul_style}}
template_args["list" .. group_index] = list
table.insert(hero_list, {
group_index = group_index + 1
name = hero["Name"],
bps = val,
shots = shots
})
end
end
end
end
end
end
-- Sort Alphabetically
table.sort(hero_list, function(a, b) return a.name < b.name end)
-- Build Table
local html = mw.html.create('table')
html:addClass('wikitable sortable mw-collapsible')
if item_name then
-- Query all Street Brawl items for this slot (regardless of cost)
html:tag('caption'):wikitext('Buildup Per Shot: ' .. item_name)
local sb_min = 0
local sb_max = 999999 -- Wide range to catch all Street Brawl items
local sb_list
if type=='get_item_nav_cards' then
sb_list = p.get_item_nav_cards(slot, sb_min, sb_max, debug_mode, "street_brawl_only")
elseif type=='get_item_nav_bulletpoints' then
sb_list = p.get_item_nav_bulletpoints(slot, sb_min, sb_max, debug_mode, "street_brawl_only")
end
end
 
-- Headers
-- Only add Street Brawl group if there are items
local headerRow = html:tag('tr')
if sb_list and sb_list ~= "" then
headerRow:tag('th'):wikitext('Hero')
template_args["group" .. group_index] = street_brawl_label
headerRow:tag('th'):wikitext('% per shot')
template_args["list" .. group_index] = sb_list
headerRow:tag('th'):wikitext('Shots to Proc')
 
-- Rows
for _, h in ipairs(hero_list) do
local row = html:tag('tr')
-- Expand HeroIcon template
local icon_template = frame:expandTemplate{ title = 'HeroIcon', args = { h.name } }
row:tag('td'):wikitext(icon_template)
row:tag('td'):wikitext(string.format("%.1f", h.bps))
row:tag('td'):wikitext(tostring(h.shots))
end
end
 
return tostring(html)
return frame:expandTemplate{title=template_title, args=template_args}
end
end


-- Main entry point for the template
-- for [[Template:Active Items]]
-- Decides whether to return a single value or a full table based on arguments
function p.generate_active_items_table(frame)
p.main = function(frame)
    local active_items = {}
local args = frame:getParent().args
   
-- Handle direct #invoke calls vs Template calls
    -- 1. Collect active items and their cost
if not args[1] and not args['item'] then args = frame.args end
    for item_key, item_data in pairs(items_data) do
 
        -- Convert cost to a number; will be nil if the JSON value is null or missing
local arg1 = args[1] or args['hero']
        local cost = tonumber(item_data["Cost"])
local arg2 = args[2] or args['item']
       
 
        if item_data["Name"] and
-- If both Hero and Item are present -> Return Single Number
          item_data["IsDisabled"] == false and
if arg1 and arg2 then
          cost ~= nil and cost > 0 and            -- FILTER: Must have a cost greater than 0
-- Manually setting args for the helper function to read
          item_data["Activation"] and  
frame.args = {arg1, arg2}
          item_data["Activation"] ~= "Passive" then
return p.get_bps(frame)
           
            table.insert(active_items, {
-- If only one arg (Item) is present -> Return Table
                name = item_data["Name"],
elseif arg1 then
                key = item_key,
frame.args = {arg1}
                cost = cost,
return p.write_buildup_table(frame)
                slot = item_data["Slot"] or "Weapon",
                has_active_desc = item_data["ActiveDescription"] ~= nil
else
            })
return "Error: Provide [Item Name] for a table, or [Hero Name] [Item Name] for a value."
        end
end
    end
   
    -- 2. Sort by name
    table.sort(active_items, function(a, b) return a.name < b.name end)
   
    -- 3. Generate wiki markup
    local wikitext = [=[
{| class="wikitable sortable" style="width:100%"
|+{{#invoke:Dictionary|translate|Active Items}}
! colspan="2" | {{#invoke:Lang|get_string|Citadel_HeroBuilds_CategoryNameLabel}}
! {{#invoke:Lang|get_string|Citadel_UserFeedback_TypeLabel}}
! {{Souls|{{#invoke:Dictionary|translate|Cost}}}}
! {{#invoke:Lang|get_string|Citadel_Mod_Tooltip_Active}}
! {{#invoke:Lang|get_string|AbilityCooldown_label}}
]=]
   
    -- 4. Add rows for each item
    for _, item in ipairs(active_items) do
        -- Determine background color and item type
        local bg_color, item_type
        if item.slot == "Armor" then
            bg_color = "#86C921"
            item_type = "Armor"
        elseif item.slot == "Tech" then
            bg_color = "#DE9CFF"
            item_type = "Tech"
        else
            bg_color = "#FCAC4D"
            item_type = "Weapon"
        end
       
        -- The cost cell uses 'data-sort-value' to provide a clean number for the client-side sorter,
        -- while the cell's visible content is formatted by the {{Souls}} template.
        wikitext = wikitext .. "\n" .. string.format([=[
|-
! style="background-color:%s" | [[File:%s.png|64x64px]]
! [[%s{{If_lang}}|{{#invoke:Lang|get_string|%s}}]]
| style="text-align:center;font-weight:bold" | {{ItemType|%s|{{#invoke:Lang|get_string|CitadelCategory%s}}}}
| data-sort-value="%d" style="text-align:center;font-size:15px" | {{Souls|%d}}
| {{#invoke:Utilities|process_variables|%s_active_desc|%s}}{{#invoke:Utilities|process_variables|%s_desc|%s}}{{#invoke:Utilities|process_variables|%s_active|%s}}
| style="text-align:center;font-size:16px" | {{#invoke:ItemData|get_prop|%s|AbilityCooldown}}s
]=],
            bg_color,
            item.name,
            item.name, item.key,
            item_type, item_type,
            item.cost, item.cost,
            item.key, item.name, item.key, item.name, item.key, item.name,
            item.name)
    end
   
    wikitext = wikitext .. "\n|}"
   
    return frame:preprocess(wikitext)
end
end


return p
return p