let count = 3; 
let tmID; 
const infobox = document.getElementById("infobox");
const startButton = document.getElementById("startButton");
const boxes = document.querySelectorAll(".box");
let targetBox;


function initGame() {
    const randomIndex = Math.floor(Math.random() * boxes.length);
    targetBox = boxes[randomIndex];

    boxes.forEach(box => {
        box.onclick = () => checkWin(box);
    });
}

function countDown() {
    if (count === 0) {
        infobox.innerHTML = "失敗です...";
        clearTimeout(tmID);
    } else {
        infobox.innerHTML = count + "秒前";
        count--;
        tmID = setTimeout(countDown, 1000);
    }
}

// ゲームのスタート
startButton.addEventListener("click", () => {
    count = 3; 
    infobox.innerHTML = "3秒前";
    initGame(); 
    countDown();
});

// ボックスのクリック判定
function checkWin(box) {
    if (box === targetBox) {
        clearTimeout(tmID);
        infobox.innerHTML = "当たり!";
    } 
}
