
function init_event()
    crates = {}

    levels = 5
    local crate = ag.loadModel("crate", {scale=0.5})
    crates[1] = crate
    offset = 0.5
    crate:setPosition(0, 0, offset + levels + 0.5)
    cratenum = 1
    for level = 2, levels do
        for x = 1, level do
            local c = crate:clone()
            c:setPosition((x - 1) * 1.5 - (level * 1.5 - 0.5)/2 + 0.5,
                0, offset + levels - level + 1.5)
            cratenum = cratenum + 1
            crates[cratenum] = c
        end
    end

    ground = ag.loadModel("crate", {static = true, scale = 10})
    ground:setPosition(0, 0, -10)
    ag.setCamera(2, -12, 8, 0, 0, 2, 0, 0, 1)

    iris = ag.loadSound("iris.mp3")
    hit_pins = ag.loadSound("hit_pins.mp3")
end

function key_down_event(key)
    if (key == "d") then
        if (cratenum >= 1) then
            local idx = math.random(cratenum)
            crates[idx]:destroy()
            for i = idx, cratenum - 1 do
                crates[i] = crates[i + 1]
            end
            crates[cratenum] = nil
            cratenum = cratenum - 1
        end
    elseif (key == "m") then
        ag.registerEventHandler(mouse_moves, "mouse_motion")
    elseif (key == "n") then
        ag.clearEventHandler("mouse_motion")
    elseif (key == "p") then
        if (playing) then
            iris:stop()
            playing = false
        else
            iris:resume()
            playing = true
        end
    elseif (key == "h") then
        hit_pins:play()
    elseif (key == "l") then
        hit_pins:loop(3)
    elseif (key == "escape" or key == "q") then
        ag.exit()
    end
end

function mouse_moves(x, y, xrel, yrel)
    ag.println("mouse_moves ", x, ", ", y)
end

function update_overlay_event()
    y = 4
    size = 16
    for i = 0, 17 do
        local message = "Hello there"
        local width, height = ag.getTextSize(message, size)
        ag.drawText(message, 1, 0.7, 0, size, 2, y)
        y = y + height + 4
        size = size + 4
    end
end
