-- duckbench - a duck-based benchmarker for Yeoldedink 0.9+

local ducks = {}
local fpses = {60}

function makeduck()
    local spr = dink.create_sprite(math.random(600), math.random(400), 3, 21, 1)
    spr.base_walk = 20
    spr.speed = 1
    spr.timing = 33
    -- spr:say("`" .. math.random(9) .. "Quack!")
    table.insert(ducks, spr)
end

function averagefps()
    local fps = 60
    for k, v in ipairs(fpses) do
        fps = fps + v
    end
    -- clear up to only process the last 1000 frames
    if #fpses > 1000 then
        fpses = {60}
    end

    return fps / #fpses
end

function main()
    current_sprite:say("`%hi")
end

function talk()
    player:freeze()
    current_sprite:say_stop("`%Starting Duckbench!")
    dink.wait(500)
    current_sprite:say_stop("`%Please do not alt+tab out or touch anything while this is running")
    dink.wait(500)
    -- put this here as music-loading can cause frame dips
    dink.playmidi("bacter_vs_saga_musix_-_the_oasis.it")
    player:say_stop("k then")
    player.dir = 2
    dink.wait(400)

    while averagefps() > 59 do
        makeduck()
        fpses[#fpses+1] = dink.get_fps()
        dink.wait(0)
        -- player:say(averagefps())
    end
    
    dink.playmidi("pod.s3m")
    local lastsprite = dink.get_last_sprite()
    
    for k, v in ipairs(ducks) do
        dink.say_xy("`0Your Duckbench score is " .. lastsprite, 0, 300)
        v.active = false
        dink.wait(0)
    end

    dink.wait(100)

    if lastsprite < 1000 then
        player:say("Well that sucks")
    else
        player:say("Cool")
    end
    
    dink.playmidi("overload.mod")
    -- reset it in case they want to run it again
    fpses = {60}
    player:unfreeze()
end