-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
60 lines (55 loc) · 1.46 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
let game = {
words: ["red", "blue", "yellow", "green"],
currentWord: "",
matchedIndex: 0,
startTime: null,
isPlaying: false,
mainArea: document.getElementById("main"),
resultArea: document.getElementById("result"),
start: function () {
game.isPlaying = true;
game.startTime = Date.now();
game.setWord();
},
setWord: function () {
game.currentWord = game.words.shift() || "";
game.matchedIndex = 0;
game.displayWord();
},
isFinished: function () {
return game.words.length === 0;
},
displayResult: function () {
const currentTime = Date.now();
const elapsedTime = formattedSeconds(currentTime - game.startTime);
game.resultArea.innerText = `${elapsedTime} 秒かかりました。\n もう一度プレイする場合にはブラウザをリロードしてください。`;
game.isPlaying = false;
},
displayWord: function () {
game.mainArea.innerText =
"_".repeat(game.matchedIndex) +
game.currentWord.substring(game.matchedIndex);
},
};
document.onclick = () => {
if (game.isPlaying === false) {
game.start();
}
};
document.onkeydown = (event) => {
if (event.key !== game.currentWord[game.matchedIndex]) {
return;
}
game.matchedIndex++;
game.displayWord();
if (game.matchedIndex === game.currentWord.length) {
if (game.isFinished()) {
game.displayResult();
}
game.setWord();
}
};
// utils
function formattedSeconds(ms) {
return (ms / 1000).toFixed(2);
}