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