CCCPaste

Bouton tactile

local state = false

-- Fonction pour dessiner le bouton switch ON/OFF centré
local function drawButton(state, text)
    term.clear()
    term.setCursorPos(1,1)
    local width, height = term.getSize()

    local bgColor = colors.red
    local fgColor = colors.white
    if state then
        bgColor = colors.green
        fgColor = colors.black
    end

    -- Dessine le fond écran tout en couleur du switch
    term.setBackgroundColor(bgColor)
    term.clear()

    -- Calcule la position du texte pour le centrer
    local textLen = #text
    local x = math.floor((width - textLen) / 2) + 1
    local y = math.floor(height / 2)

    term.setCursorPos(x, y)
    term.setTextColor(fgColor)
    term.write(text)
end

-- Fonction d’attente d’un clic tactile, retourne true si sur le bouton
local function waitTouch()
    local width, height = term.getSize()
    local buttonY = math.floor(height / 2)
    while true do
        local event, side, x, y = os.pullEvent("monitor_touch")
        -- Sur pocket computer c’est “mouse_click” avec coordonnées x, y
        if event == "mouse_click" then  
            -- Vérifie si y correspond à la ligne du bouton
            if y == buttonY then
                return true
            end
        end
    end
end

-- Programme principal
while true do
    if state then
        drawButton(true, "ON")
    else
        drawButton(false, "OFF")
    end

    -- Attend un clic (toucher) clavier de l’utilisateur
    local event, button, x, y = os.pullEvent("mouse_click")
    local width, height = term.getSize()
    local buttonY = math.floor(height / 2)
    if y == buttonY then
        state = not state -- Change l’état
    end
end