'use strict';
{
const words = [
'apple',
'sky',
'blue',
'middle',
'set'
];
let word;
let loc;
let score;
let miss;
const timeLimit = 3 * 1000;
let startTime;
let isPlaying = false;
const target = document.getElementById('target');
const scoreLabel = document.getElementById('score');
const missLabel = document.getElementById('miss');
const timerLabel = document.getElementById('timer');
// 新しく作って切り出した関数
function init() {
loc = 0;
score = 0;
miss = 0;
scoreLabel.textContent = score;
missLabel.textContent = miss;
word = words[Math.floor(Math.random() * words.length)];
}
function updateTarget() {
let placeholder = '';
for (let i = 0; i < loc; i++) {
placeholder += '_';
}
target.textContent = placeholder + word.substring(loc);
}
function updateTimer() {
const timeLeft = startTime + timeLimit - Date.now();
timerLabel.textContent = (timeLeft / 1000).toFixed(2);
const timeoutId = setTimeout(() => {
updateTimer();
}, 10);
if (timeLeft < 0) {
isPlaying = false;
clearTimeout(timeoutId);
timerLabel.textContent = '0.00';
setTimeout(() => {
showResult();
}, 10);
target.textContent = 'click to replay'
}
}
function showResult() {
const accuracy = score + miss === 0 ? 0 : score / (score + miss) * 100;
alert(`${score} letters, ${miss} misses, ${accuracy.toFixed(2)}% accuracy!`);
}
// このイベントの中の処理の一部を関数init()として切り出しました
window.addEventListener('click', () => {
if (isPlaying === true) {
return;
}
isPlaying = true;
target.textContent = word;
startTime = Date.now();
// 関数init() 呼び出し
init();
updateTimer();
});
window.addEventListener('keydown', e => {
if (isPlaying !== true) {
return;
}
if (e.key === word[loc]) {
loc++;
if (loc === word.length) {
word = words[Math.floor(Math.random() * words.length)];
loc = 0;
}
updateTarget();
score++;
scoreLabel.textContent = score;
} else {
miss++;
missLabel.textContent = miss;
}
});
}