Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
253 lines (206 loc) · 7.32 KB
/
Copy pathscript.js
File metadata and controls
253 lines (206 loc) · 7.32 KB
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// DOM Elements
const startBtn = document.getElementById("start");
const resetBtn = document.getElementById("reset");
const timerEl = document.getElementById("timer");
const wpmEl = document.getElementById("wpm");
const accuracyEl = document.getElementById("accuracy");
const typingspace = document.getElementById("typingspace");
const instruction = document.getElementById("instruction");
const resultsCard = document.getElementById("results");
const finalWpmEl = document.getElementById("final-wpm");
const finalAccuracyEl = document.getElementById("final-accuracy");
const finalKeysEl = document.getElementById("final-keys");
// State Variables
let timeRemaining = 30;
let timerInterval = null;
let currentLetterIndex = 0;
let totalLength = 0;
let isPlaying = false;
let isGameOver = false;
let correctKeystrokes = 0;
let totalKeystrokes = 0;
// Typing Sentences Bank
const sentences = [
"JavaScript is one of the most popular programming languages in the world.",
"Learning data structures and algorithms improves problem-solving skills.",
"Backend developers build scalable and secure server-side applications.",
"The event loop allows JavaScript to handle asynchronous operations efficiently.",
"Practice coding every day to become more confident in programming interviews.",
"Spring Boot simplifies the development of production-ready Java applications.",
"Arrays are ordered collections that can store multiple values in a single variable.",
"Understanding execution contexts and closures is essential for mastering JavaScript.",
"Building real-world projects helps reinforce concepts learned from tutorials.",
"Consistency and patience are more important than studying for long hours occasionally."
];
// Initialize buttons and layouts
resetBtn.classList.add("hidden");
// Start the game typing session
function startTyping() {
if (isPlaying) return;
// Update state
isPlaying = true;
isGameOver = false;
timeRemaining = 30;
currentLetterIndex = 0;
correctKeystrokes = 0;
totalKeystrokes = 0;
// UI state updates
instruction.classList.add("opacity-0");
setTimeout(() => {
instruction.classList.add("hidden");
}, 300);
resultsCard.classList.add("hidden");
resultsCard.classList.remove("flex");
startBtn.classList.add("hidden");
resetBtn.classList.remove("hidden");
// Choose random sentence
const randIndex = Math.floor(Math.random() * sentences.length);
const sentence = sentences[randIndex];
// Render character spans
typingspace.innerHTML = "";
const charArray = [...sentence];
totalLength = charArray.length;
charArray.forEach((char, index) => {
const span = document.createElement("span");
span.textContent = char;
span.id = `char-${index}`;
span.className = "char-untyped";
typingspace.appendChild(span);
});
// Activate first character
const firstChar = document.getElementById("char-0");
if (firstChar) {
firstChar.classList.add("char-active");
}
// Visual state for active writing space
typingspace.classList.remove("opacity-40", "select-none", "pointer-events-none");
// Reset live stats UI
timerEl.textContent = `${timeRemaining}s`;
wpmEl.textContent = "0";
accuracyEl.textContent = "100%";
// Start countdown clock
clearInterval(timerInterval);
clock();
}
// Countdown Clock timer
function clock() {
timerInterval = setInterval(() => {
timeRemaining--;
timerEl.textContent = `${timeRemaining}s`;
// Live WPM calculation
updateLiveStats();
if (timeRemaining <= 0) {
clearInterval(timerInterval);
endGame();
}
}, 1000);
}
// Compute live Speed and Accuracy
function updateLiveStats() {
const elapsedSeconds = 30 - timeRemaining;
const elapsedMinutes = elapsedSeconds > 0 ? elapsedSeconds / 60 : 1 / 60;
// WPM = (correct character count / 5) / elapsed minutes
const currentWpm = Math.round((correctKeystrokes / 5) / elapsedMinutes);
wpmEl.textContent = currentWpm;
// Accuracy = (correct keystrokes / total keystrokes) * 100
const accuracy = totalKeystrokes > 0 ? Math.round((correctKeystrokes / totalKeystrokes) * 100) : 100;
accuracyEl.textContent = `${accuracy}%`;
}
// Conclude the practice session
function endGame() {
isPlaying = false;
isGameOver = true;
clearInterval(timerInterval);
// Dim typingspace
typingspace.classList.add("opacity-40", "select-none", "pointer-events-none");
// Calculate final stats
const elapsedSeconds = 30 - timeRemaining;
const elapsedMinutes = elapsedSeconds > 0 ? elapsedSeconds / 60 : 1 / 60;
const finalWpm = Math.round((correctKeystrokes / 5) / elapsedMinutes);
const finalAccuracy = totalKeystrokes > 0 ? Math.round((correctKeystrokes / totalKeystrokes) * 100) : 100;
// Display results card
finalWpmEl.textContent = finalWpm;
finalAccuracyEl.textContent = `${finalAccuracy}%`;
finalKeysEl.textContent = correctKeystrokes;
resultsCard.classList.remove("hidden");
resultsCard.classList.add("flex");
}
// Restore typing state to clean interface
function resetGame() {
clearInterval(timerInterval);
// Reset state values
isPlaying = false;
isGameOver = false;
timeRemaining = 30;
currentLetterIndex = 0;
totalLength = 0;
correctKeystrokes = 0;
totalKeystrokes = 0;
// Clear workspace UI
typingspace.innerHTML = "";
typingspace.classList.add("opacity-40", "select-none", "pointer-events-none");
timerEl.textContent = "30s";
wpmEl.textContent = "0";
accuracyEl.textContent = "100%";
// Reset button visibility
startBtn.classList.remove("hidden");
resetBtn.classList.add("hidden");
// Show instruction overlay
instruction.classList.remove("hidden");
// Small timeout to allow transition to register
setTimeout(() => {
instruction.classList.remove("opacity-0");
}, 10);
// Hide results
resultsCard.classList.add("hidden");
resultsCard.classList.remove("flex");
}
// Global Keyboard Handler
function handleKeyDown(event) {
// Shortcut keys
if (event.key === "Enter" && !isPlaying) {
event.preventDefault();
startTyping();
return;
}
if (event.key === "Escape" && isPlaying) {
event.preventDefault();
resetGame();
return;
}
// Only handle typing input during active gameplay
if (!isPlaying || isGameOver) return;
const keyname = event.key;
// We only check printable character key strokes (length 1)
if (keyname.length !== 1) return;
// Increment total keystrokes made
totalKeystrokes++;
const currentLetterSpan = document.getElementById(`char-${currentLetterIndex}`);
if (!currentLetterSpan) return;
const expectedChar = currentLetterSpan.textContent;
if (keyname === expectedChar) {
// Correct keystroke
correctKeystrokes++;
currentLetterSpan.className = "char-correct";
// Advance index
currentLetterIndex++;
if (currentLetterIndex < totalLength) {
const nextLetterSpan = document.getElementById(`char-${currentLetterIndex}`);
if (nextLetterSpan) {
nextLetterSpan.classList.add("char-active");
}
} else {
// Completed last letter of the sentence
endGame();
}
} else {
// Incorrect keystroke
currentLetterSpan.classList.add("char-incorrect");
}
// Live update the stats panel
updateLiveStats();
}
// Event Listeners
startBtn.addEventListener("click", startTyping);
resetBtn.addEventListener("click", resetGame);
document.addEventListener("keydown", handleKeyDown);