local getArgs = require('Module:Arguments').getArgs
local data = require('Module:ImasIcon/Gakuen/Data') -- 引入角色數據
local p = {}
-- 預建小寫名稱到ID的映射表
local nameToId = {}
for name, id in pairs(data) do
nameToId[name:lower()] = id
end
-- 常量定義
local DEFAULT_SIZE = 150
local MIN_SIZE = 20
local MAX_SIZE = 300
local DEFAULT_ID = 0
local SPRITE_COLS = 6
-- 根據輸入獲取角色編號
local function getCharacterId(input)
if not input or input == "" then
return DEFAULT_ID, "未提供角色參數"
end
-- 嘗試直接轉換為數字
local num = tonumber(input)
if num then
return (num > 0) and num or DEFAULT_ID,
(num <= 0) and "無效角色ID:" .. input or nil
end
-- 從預建索引中查找名稱
local id = nameToId[input:lower()]
if id then
return id, nil
end
return DEFAULT_ID, "無效角色名稱:" .. input
end
function p.main(frame)
local args = getArgs(frame)
local id, errorMsg = getCharacterId(args[1])
local isValidId = id > 0
-- 處理尺寸參數並限制範圍
local size = tonumber(args[2]) or DEFAULT_SIZE
size = math.max(MIN_SIZE, math.min(size, MAX_SIZE))
-- 構建類名集合
local classes = {"imas-gakuen-sprite", "gakuen-sprite-circle"}
if not isValidId then
table.insert(classes, "gakuen-sprite-error")
end
if args.class then
table.insert(classes, args.class)
end
-- 計算背景位置
local bgSize, bgPos
if isValidId then
local col = (id - 1) % SPRITE_COLS
local row = math.floor((id - 1) / SPRITE_COLS)
bgSize = string.format("%dpx", SPRITE_COLS * size)
bgPos = string.format("%dpx %dpx", -col * size, -row * size)
else
bgSize = "0 0"
bgPos = "0 0"
end
-- 構建樣式
local styles = {
string.format("height:%dpx;", size),
string.format("width:%dpx;", size),
string.format("background-size:%s;", bgSize),
string.format("background-position:%s;", bgPos),
args.style or ""
}
-- 生成HTML
return string.format(
'<span class="%s" style="%s" title="%s"></span>',
table.concat(classes, " "),
table.concat(styles),
errorMsg or ""
)
end
return p