Module:Dice/Format

From Caves of Qud Wiki
Jump to navigation Jump to search

require 'math'
local Dice = require'Module:Dice'

local DiceFormat = {}

function DiceFormat.diceStats(frame)
    local dice = Dice.parse(frame.args.roll)

	local template_title = (frame.args.template ~= nil and frame.args.template ~= '') and frame.args.template or 'Dice string'
	local mult = (frame.args.multiplier ~= nil and frame.args.multiplier ~= '') and frame.args.multiplier or 1
	local extra_afterroll = (frame.args.extraafterroll ~= nil and frame.args.extraafterroll ~= '') and frame.args.extraafterroll or 0

    local average = dice:average() * mult + extra_afterroll
    local average_truncated = ('%d'):format(average)
    local maximum = dice:maximum() * mult + extra_afterroll
    local minimum = dice:minimum() * mult + extra_afterroll
    local range = dice:range() * mult
    local variance = dice:variance() * mult
    
    -- For character stats which have a multiplier, the game rounds up to the
    -- nearest integer; this also affects the calculated average. These values
    -- are used by Template:Character/Attribute and /DetailedAttribute.
    local maximum_ceil = math.floor(maximum + 0.5)
    local minimum_ceil = math.floor(minimum + 0.5)
    local ceil_based_average = (maximum_ceil + minimum_ceil) / 2.0
    local ceil_based_average_truncated = ('%d'):format(ceil_based_average)

    return frame:expandTemplate{
        title = template_title,
        args = {
            average = average,
            average_truncated = average_truncated,
            maximum = maximum,
            minimum = minimum,
            range = range,
            variance = variance,
            maximum_ceil = maximum_ceil,
            minimum_ceil = minimum_ceil,
            ceil_based_average = ceil_based_average,
            ceil_based_average_truncated = ceil_based_average_truncated,

            -- for backwards compatibility
            mean = average,
            mean_truncated = average_truncated,
        },
    }
end

return DiceFormat