local w, h = term.getSize()
term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
term.clear()

local birdX = 8
local birdY = math.floor(h / 2)
local velocity = 0
local gravity = 0.35
local jumpPower = -2.2

local pipes = {}
local pipeGap = 6
local pipeSpeed = 1
local spawnTimer = 0
local score = 0
local gameOver = false

local function draw()
    term.setBackgroundColor(colors.black)
    term.clear()

    -- Score
    term.setCursorPos(2, 1)
    term.setTextColor(colors.yellow)
    write("Score: " .. score)

    -- Bird
    term.setCursorPos(birdX, math.floor(birdY))
    term.setTextColor(colors.yellow)
    write("@")

    -- Pipes
    term.setTextColor(colors.green)
    for _, pipe in ipairs(pipes) do
        for y = 2, h do
            if y < pipe.gapY or y > pipe.gapY + pipeGap then
                if pipe.x >= 1 and pipe.x <= w then
                    term.setCursorPos(pipe.x, y)
                    write("|")
                end
            end
        end
    end
end

local function addPipe()
    local gapY = math.random(3, h - pipeGap - 2)
    table.insert(pipes, {
        x = w,
        gapY = gapY,
        scored = false
    })
end

local function update()
    velocity = velocity + gravity
    birdY = birdY + velocity

    if birdY < 2 or birdY > h then
        gameOver = true
    end

    spawnTimer = spawnTimer + 1
    if spawnTimer >= 12 then
        addPipe()
        spawnTimer = 0
    end

    for i = #pipes, 1, -1 do
        local pipe = pipes[i]
        pipe.x = pipe.x - pipeSpeed

        if pipe.x == birdX then
            local by = math.floor(birdY)
            if by < pipe.gapY or by > pipe.gapY + pipeGap then
                gameOver = true
            end
        end

        if not pipe.scored and pipe.x < birdX then
            score = score + 1
            pipe.scored = true
        end

        if pipe.x < 1 then
            table.remove(pipes, i)
        end
    end
end

local function input()
    while not gameOver do
        local event, key = os.pullEvent("key")
        if key == keys.space or key == keys.up or key == keys.w then
            velocity = jumpPower
        elseif key == keys.q then
            gameOver = true
        end
    end
end

local function gameLoop()
    while not gameOver do
        update()
        draw()
        sleep(0.08)
    end
end

parallel.waitForAny(input, gameLoop)

term.setBackgroundColor(colors.black)
term.clear()
term.setCursorPos(math.floor(w / 2) - 5, math.floor(h / 2))
term.setTextColor(colors.red)
write("GAME OVER")

term.setCursorPos(math.floor(w / 2) - 6, math.floor(h / 2) + 1)
term.setTextColor(colors.white)
write("Score: " .. score)

term.setCursorPos(1, h)