Newer
Older
Program-Storage / typing / javascript.js
const CLASSNAME = "-visible";
const TIMEOUT = 2000;
const $target = $(".bg");

setInterval(() => {
  $target.addClass(CLASSNAME);

  setTimeout(() => {
    $target.removeClass(CLASSNAME);
  }, TIMEOUT);
}, TIMEOUT*2);

let problem = [];
let currentQuestion;
let score = 0;
let time = 10;
let isPlyaing = false;
let countdown;

const wordDisplay = document.getElementById('word')
const input = document.getElementById('input')
const scoreDisplay = document.getElementByid('score')
const timeDisplay = document.getElementByid('time')
const startButton = document.getElementByid('start')
const resetButton = document.getElementByid('reset')

function init(){
    loadCSV('JavaScript.csv',(data) => {
	questions = data;
	showWord();
	input.addEventListener('input', startMatch);
	startButton.addEventListener('click', startGame);
	resetButton.addEventListener('click', resetGame);
    });
}

function loadCSV(file, callback) {
    fetch(file)
	.then(response => response.text())
	.then(text => {
	    const lines = text.split(' \n' );
	    const data = lines.map(line => {
		const [question, answer] = line.split( ',' );
		return { question, answer };
	    });
	    callback(data);
	});
}

function startGame(){
    if (!isPlaying){
	isPlaying = true;
	time = 10;
	score = 0;
	showWord();
	input.value = '';
	input.focus();
	updateScore();
	updatetTime();
	countdown = setInterval(updatetime, 1000);
	setTimeout(() => {
	    clearInterval(countdown);
	    isPlaying = false;
	    wordDisplay.innerText = '終了';
	}, time * 1000);
    }
}

function showWord(){
    const randIndex = Math.floor(Math.random() * questions.length);
    currentQuestion = questions[randIndex];
    wordDisplay.innerText = currentQuestion.question;
}

function startMatch(){
    if (matchWords()){
	score++;
	updateScore();
	showWord();
	input.value = '';
    }
}

function updateScore(){
    scoreDisplay.innerText = score;
}

function updateTime(){
    time--;
    timeDisplay.innerText = time;
}

function resetGame(){
    isPlaying = false;
    score = 0;
    clearInterval(countdown);
    time = 10;
    showWord();
    input.value = '';
    updateScore();
    updateTime();
    wordDisplay.innerText='スタートボタンを押してね'
}

function matchWords(){
    return input.value === currentQuestion.answer.trim();
}

init();