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');
const exam1Elem = document.getElementById('exam1');
const exam2Elem = document.getElementById('exam2');
const exam3Elem = document.getElementById('exam3');
const exam4Elem = document.getElementById('exam4');
let questions = [];
let currentQuestion = {};
let timer;
let timeLeft = 20;
let questionCount = 0;
const maxQuestions = 10;
let score = 0;
startButton.addEventListener('click', () => {
startButton.style.display = 'none';
gameDiv.style.display = 'block';
loadQuestions('pr-ad.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, ex1, ex2, ex3, ex4] = line.split(',');
return { question, answer, ex1, ex2, ex3, ex4 };
});
}
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;
exam1Elem.textContent = currentQuestion.ex1 || '';
exam2Elem.textContent = currentQuestion.ex2 || '';
exam3Elem.textContent = currentQuestion.ex3 || '';
exam4Elem.textContent = currentQuestion.ex4 || '';
answerInput.value = '';
answerInput.focus();
}
function checkAnswer() {
if (answerInput.value === currentQuestion.answer) {
score++;
questions = questions.filter(q => q !== currentQuestion);
nextQuestion();
resetTimer();
} else {
answerInput.value = '';
}
}
function startTimer() {
timeLeft = 20;
timerElem.textContent = timeLeft;
timer = setInterval(() => {
timeLeft--;
timerElem.textContent = timeLeft;
if (timeLeft <= 0) {
clearInterval(timer);
alert(`時間切れです!正解は:${currentQuestion.answer}。現在の得点:${score}`);
nextQuestion();
resetTimer();
}
}, 1000);
}
function resetTimer() {
clearInterval(timer);
startTimer();
}
function endGame() {
alert(`ゲーム終了!あなたのスコアは${score}点です`);
startButton.style.display = 'block';
gameDiv.style.display = 'none';
clearInterval(timer);
}
});