Newer
Older
2024-naoki / bakudan.js
document.addEventListener('DOMContentLoaded', () => {
    const gameContainer = document.getElementById('game-container');
    const startButton = document.getElementById('startbotan');
    const boxes = document.querySelectorAll('.bakuhatu');
    const resultDisplay = document.getElementById("result");
    let winningBox;
    let countdown;
    let timeLeft;

    function startGame() {
        startButton.disabled = true;
        timeLeft = 3;
        winningBox = Math.floor(Math.random() * boxes.length) + 1;
    const resultDisplay = document.getElementById("result");
        
        boxes.forEach(box => {
            box.addEventListener('click', checkBox);
            box.style.backgroundColor = '#300d2e';
        });

        countdown = setInterval(() => {
            timeLeft--;
            updateCountdown();
            if (timeLeft === 0) {
                endGame(false);
            }
        }, 1000);

        updateCountdown();
    }

    function checkBox(event) {
        const clickedBox = parseInt(event.target.textContent);
        if (clickedBox === winningBox) {
            endGame(true);
        }
    }

    function endGame(isWin) {
        clearInterval(countdown);
        boxes.forEach(box => box.removeEventListener('click', checkBox));
        
        if (isWin) {
            resultDisplay.textContent = 'おめでとう!あったり〜!';
            boxes[winningBox - 1].style.backgroundColor = 'green';
        } else {
            resultDisplay.textContent = '残念でした!';
            boxes[winningBox - 1].style.backgroundColor = 'red';
        }

        startButton.disabled = false;
	 startButton.textContent = '再挑戦する?';
    }

    function updateCountdown() {
        const countdownDisplay = document.createElement('div');
        countdownDisplay.id = 'countdown';
        countdownDisplay.textContent = `${timeLeft}秒前...`;
        
        const existingCountdown = document.getElementById('countdown');
        if (existingCountdown) {
            existingCountdown.remove();
        }
        
        gameContainer.insertAdjacentElement('afterend', countdownDisplay);
    }

    startButton.addEventListener('click', startGame);
});