-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.js
126 lines (113 loc) · 2.51 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
window.addEventListener('load', init);
// Globals
// Available Levels
const levels = {
easy: 4,
medium: 3,
hard: 2
};
// To change level
const currentLevel = levels.easy;
let time = currentLevel;
let score = 0;
let isPlaying;
// DOM Elements
const wordInput = document.querySelector('#word-input');
const currentWord = document.querySelector('#current-word');
const scoreDisplay = document.querySelector('#score');
const timeDisplay = document.querySelector('#time');
const message = document.querySelector('#message');
const seconds = document.querySelector('#seconds');
const words = [
'hat',
'river',
'lucky',
'statue',
'generate',
'stubborn',
'cocktail',
'runaway',
'joke',
'developer',
'establishment',
'hero',
'javascript',
'nutrition',
'revolver',
'echo',
'siblings',
'investigate',
'horrendous',
'symptom',
'laughter',
'magic',
'master',
'space',
'definition'
];
// Initialize Game
function init() {
// Show number of seconds in UI
seconds.innerHTML = currentLevel;
// Load word from array
showWord(words);
// Start matching on word input
wordInput.addEventListener('input', startMatch);
// Call countdown every second
setInterval(countdown, 1000);
// Check game status
setInterval(checkStatus, 50);
}
// Start match
function startMatch() {
if (matchWords()) {
isPlaying = true;
time = currentLevel + 1;
showWord(words);
wordInput.value = '';
score++;
}
// If score is -1, display 0
if (score === -1) {
scoreDisplay.innerHTML = 0;
} else {
scoreDisplay.innerHTML = score;
}
}
// Match currentWord to wordInput
function matchWords() {
if (wordInput.value === currentWord.innerHTML) {
message.innerHTML = 'Correct!!!';
return true;
} else {
message.innerHTML = '';
return false;
}
}
// Pick & show random word
function showWord(words) {
// Generate random array index
const randIndex = Math.floor(Math.random() * words.length);
// Output random word
currentWord.innerHTML = words[randIndex];
}
// Countdown timer
function countdown() {
// Make sure time is not run out
if (time > 0) {
// Decrement
time--;
} else if (time === 0) {
// Game is over
isPlaying = false;
}
// Show time
timeDisplay.innerHTML = time;
}
// Check game status
function checkStatus() {
if (!isPlaying && time === 0) {
message.innerHTML = 'Game Over!!!';
score = -1;
}
}