-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
271 lines (254 loc) · 9.73 KB
/
main.js
File metadata and controls
271 lines (254 loc) · 9.73 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// Sample texts for typing test
const sampleTexts = [
"The quick brown fox jumps over the lazy dog. Programming is the process of creating a set of instructions that tell a computer how to perform a task.",
"JavaScript is a high-level, interpreted programming language that conforms to the ECMAScript specification. It is a language that is also characterized as dynamic, weakly typed, prototype-based and multi-paradigm.",
"Web development is the work involved in developing a website for the Internet or an intranet. Web development can range from developing a simple single static page of plain text to complex web applications.",
"HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets and scripting languages such as JavaScript.",
"CSS is a style sheet language used for describing the presentation of a document written in a markup language such as HTML. CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript."
];
// DOM Elements
const terminalContent = document.getElementById('terminal-content');
const mobileInput = document.getElementById('mobile-input');
// Game state
let isPlaying = false;
let currentText = '';
let startTime = null;
let firstKeyTime = null;
let correctChars = 0;
let totalChars = 0;
let stats = {
testsCompleted: 0,
averageWPM: 0,
averageAccuracy: 0,
bestWPM: 0
};
// Input state
let currentInput = '';
let currentLine = null;
let mode = 'command'; // 'command', 'typing', 'yn'
function addOutput(text, className = '') {
const output = document.createElement('div');
output.className = `command-output ${className}`;
output.textContent = text;
terminalContent.appendChild(output);
terminalContent.scrollTop = terminalContent.scrollHeight;
}
function isMobile() {
return /Android|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i.test(navigator.userAgent);
}
// Always focus the hidden input on prompt creation and on terminal click/tap
function focusInput() {
setTimeout(() => mobileInput.focus(), 0);
}
terminalContent.addEventListener('click', focusInput);
// Handle input event for all typing (desktop and mobile)
mobileInput.addEventListener('input', (e) => {
if (!currentLine) return;
currentInput = e.target.value;
updatePrompt();
});
// Handle Enter key for all typing (desktop and mobile)
mobileInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
const input = currentInput;
removePrompt();
if (mode === 'command') {
addOutput(`Dev@Devtype.rushiraj.top:~$ ${input}`);
handleCommand(input);
} else if (mode === 'typing') {
handleTyping(input);
} else if (mode === 'yn') {
handleYN(input);
}
currentInput = '';
mobileInput.value = '';
e.preventDefault();
} else if (e.key === 'Backspace') {
// Handled by input event, but keep for completeness
setTimeout(() => {
currentInput = mobileInput.value;
updatePrompt();
}, 0);
} else if (e.key.length === 1) {
if (mode === 'typing' && !firstKeyTime) {
firstKeyTime = Date.now();
}
setTimeout(() => {
currentInput = mobileInput.value;
updatePrompt();
}, 0);
}
});
function addPrompt(input = '') {
removePrompt();
const commandLine = document.createElement('div');
commandLine.className = 'command-line';
commandLine.innerHTML = `
<span class="prompt">Dev@Devtype.rushiraj.top:~$</span>
<span class="user-input">${input}</span><span class="cursor"></span>
`;
terminalContent.appendChild(commandLine);
currentLine = commandLine;
currentInput = input;
terminalContent.scrollTop = terminalContent.scrollHeight;
mobileInput.value = input;
focusInput();
}
function removePrompt() {
// Remove any existing prompt
const prompts = terminalContent.querySelectorAll('.command-line');
prompts.forEach(p => p.remove());
}
const commands = {
help: () => {
addOutput(`Available commands:
start - Start a new typing test
stats - Show your typing statistics
clear - Clear the terminal
reset - Reset all statistics
exit - Exit the typing test
help - Show this help message`, 'info');
},
start: () => {
if (isPlaying || mode === 'typing') {
addOutput('A test is already in progress!', 'error');
return;
}
currentText = sampleTexts[Math.floor(Math.random() * sampleTexts.length)];
addOutput('Type the following text:', 'info');
addOutput(currentText, 'typing-text');
isPlaying = true;
mode = 'typing';
startTime = null;
firstKeyTime = null;
correctChars = 0;
totalChars = 0;
currentInput = '';
addPrompt();
},
stats: () => {
if (stats.testsCompleted === 0) {
addOutput('No tests completed yet!', 'info');
return;
}
addOutput(`Statistics:
Tests Completed: ${stats.testsCompleted}
Average WPM: ${stats.averageWPM.toFixed(1)}
Average Accuracy: ${stats.averageAccuracy.toFixed(1)}%
Best WPM: ${stats.bestWPM}`, 'info');
},
clear: () => {
terminalContent.innerHTML = '';
const welcomeMessage = document.createElement('div');
welcomeMessage.className = 'welcome-message';
welcomeMessage.textContent = 'Welcome to Windows Terminal Typing Test v1.0.0\nType \'help\' to see available commands';
terminalContent.appendChild(welcomeMessage);
},
reset: () => {
stats = {
testsCompleted: 0,
averageWPM: 0,
averageAccuracy: 0,
bestWPM: 0
};
addOutput('Statistics have been reset!', 'success');
},
exit: () => {
if (isPlaying || mode === 'typing') {
addOutput('Cannot exit while a test is in progress!', 'error');
return;
}
addOutput('Goodbye!', 'info');
setTimeout(() => {
window.close();
}, 1000);
}
};
function handleCommand(command) {
if (command.trim() === '') {
addPrompt();
return;
}
const cmd = command.trim().toLowerCase();
if (commands[cmd]) {
commands[cmd]();
} else {
addOutput(`Command not found: ${command}. Type 'help' for available commands.`, 'error');
}
if (mode === 'command') addPrompt();
}
function handleTyping(input) {
// Always append the user's input as a new line
addOutput(`Dev@Devtype.rushiraj.top:~$ ${input}`);
// Start timer on first key if not already started
if (!firstKeyTime) {
firstKeyTime = startTime = Date.now();
}
// Evaluate typing
const endTime = Date.now();
const elapsedMs = endTime - firstKeyTime;
const elapsedMin = elapsedMs / 1000 / 60;
const elapsedSec = (elapsedMs / 1000).toFixed(2);
totalChars = input.length;
let correct = 0;
let incorrect = 0;
// --- Monkeytype-style word analysis ---
const promptWords = currentText.trim().split(/\s+/);
const inputWords = input.trim().split(/\s+/);
let correctWords = 0;
let incorrectWords = 0;
for (let i = 0; i < inputWords.length; i++) {
if (promptWords[i] && inputWords[i] === promptWords[i]) {
correctWords++;
} else {
incorrectWords++;
}
}
// Character stats
for (let i = 0; i < input.length; i++) {
if (input[i] === currentText[i]) correct++;
else incorrect++;
}
correctChars = correct;
// Raw WPM: all words typed per minute
const rawWPM = elapsedMin > 0 ? Math.round(inputWords.length / elapsedMin) : 0;
// WPM: correct words per minute
const wpm = elapsedMin > 0 ? Math.round(correctWords / elapsedMin) : 0;
// CPM: correct characters per minute
const cpm = elapsedMin > 0 ? Math.round(correctChars / elapsedMin) : 0;
// Accuracy: correct words / total words typed
const accuracy = inputWords.length > 0 ? Math.round((correctWords / inputWords.length) * 100) : 0;
addOutput(`\nTest completed!\n Raw WPM: ${rawWPM}\n WPM (after accuracy): ${wpm}\n CPM: ${cpm}\n Accuracy: ${accuracy}%\n Time: ${elapsedSec} seconds\n Words Typed: ${inputWords.length}\n Correct Words: ${correctWords}\n Incorrect Words: ${incorrectWords}\n Total Characters: ${totalChars}\n Correct Characters: ${correct}\n Incorrect Characters: ${incorrect}`, 'success');
stats.testsCompleted++;
stats.averageWPM = (stats.averageWPM * (stats.testsCompleted - 1) + wpm) / stats.testsCompleted;
stats.averageAccuracy = (stats.averageAccuracy * (stats.testsCompleted - 1) + accuracy) / stats.testsCompleted;
stats.bestWPM = Math.max(stats.bestWPM, wpm);
isPlaying = false;
mode = 'yn';
addOutput('\nWould you like to try another test? (y/n)', 'info');
addPrompt();
}
function handleYN(input) {
// Always append the user's input as a new line
addOutput(`Dev@Devtype.rushiraj.top:~$ ${input}`);
const ans = input.trim().toLowerCase();
if (ans === 'y') {
mode = 'command';
commands.start();
} else if (ans === 'n') {
mode = 'command';
addOutput('Test session ended.', 'info');
addPrompt();
} else {
addOutput("Please type 'y' or 'n' only.", 'error');
addPrompt();
}
}
function updatePrompt() {
if (!currentLine) return;
const userInput = currentLine.querySelector('.user-input');
if (userInput) userInput.textContent = currentInput;
mobileInput.value = currentInput;
}
// Initial load
addPrompt();