Newer
Older
Program-Storage / typing / ruby.js
@Abe Mizuki Abe Mizuki on 14 Aug 2024 2 KB Create ruby.js
document.addEventListener('DOMContentLoaded', () => {
    const startButton = document.getElementById('startButton');
    const gameDiv = document.getElementById('game');
    const questionElem = document.getElementById('question');
    const answerForm = document.getElementById('answerForm');
    const answerInput = document.getElementById('answerInput');
    const timerElem = document.getElementById('timeLeft');
 
    let questions = [];
    let currentQuestion = {};
    let timer;
    let timeLeft = 10;
    let questionCount = 0;
    const maxQuestions = 16;
 
    startButton.addEventListener('click', () => {
        startButton.style.display = 'none';
        gameDiv.style.display = 'block';
        loadQuestions('ruby.csv');  
    });
 
    answerForm.addEventListener('submit', (e) => {
        e.preventDefault();
        checkAnswer();
    });
 
    function loadQuestions(file) {
        fetch(file)
            .then(response => response.text())
            .then(data => {
                questions = parseCSV(data);
                nextQuestion();
                startTimer();
            })
            .catch(error => console.error('Error loading questions:', error));
    }
 
    function parseCSV(data) {
        const lines = data.split('\n').slice(1); // ヘッダー行をスキップ
        return lines.map(line => {
            const [question, answer] = line.split(',');
            return { question, answer };
        });
    }
 
    function nextQuestion() {
        if (questionCount >= maxQuestions || questions.length === 0) {
            endGame();
            return;
        }
        questionCount++;
        const randomIndex = Math.floor(Math.random() * questions.length);
        currentQuestion = questions[randomIndex];
        questionElem.textContent = currentQuestion.question;
        answerInput.value = '';
        answerInput.focus();
    }
 
    function checkAnswer() {
        if (answerInput.value === currentQuestion.answer) {
            questions = questions.filter(q => q !== currentQuestion);
            nextQuestion();
            resetTimer();
        } else {
            answerInput.value = '';
        }
    }
 
    function startTimer() {
        timeLeft = 10;
        timerElem.textContent = timeLeft;
        timer = setInterval(() => {
            timeLeft--;
            timerElem.textContent = timeLeft;
            if (timeLeft <= 0) {
                clearInterval(timer);
                endGame();
            }
        }, 1000);
    }
 
    function resetTimer() {
        clearInterval(timer);
        startTimer();
    }
 
    function endGame() {
        alert('ゲーム終了');
        startButton.style.display = 'block';
        gameDiv.style.display = 'none';
        clearInterval(timer);
    }
});