-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameUI.js
382 lines (309 loc) · 12.4 KB
/
GameUI.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
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import Game from "./Game.js";
import { SessionLength } from "./SessionLength.js";
const ANSWER_TIME_LIMIT = document.getElementById("answer-time-limit");
const FACTOR_1_MIN = document.getElementById("factor-1-min");
const FACTOR_1_MAX = document.getElementById("factor-1-max");
const FACTOR_2_MIN = document.getElementById("factor-2-min");
const FACTOR_2_MAX = document.getElementById("factor-2-max");
const SESSION_LENGTH_TYPE = document.querySelectorAll('input[name="session-length-type"]');
const SESSION_LENGTH_TIME = document.getElementById("session-length-time");
const SESSION_LENGTH_COUNT = document.getElementById("session-length-count");
const SESSION_TIMER_DISPLAY = document.getElementById("session-timer-display");
const SCORE = document.getElementById("score");
const ANSWER_TIMER_DISPLAY = document.getElementById("answer-timer-display");
const QUESTION = document.getElementById("question");
const ANSWER = document.getElementById("answer");
const PAUSE_RESUME = document.getElementById("pause-resume");
const RESET = document.getElementById("reset");
const NUMPAD_BUTTONS = document.querySelectorAll(".numpad button");
// Num questions only matches up with session length at 5 FPS or less? Even 5 often gives 1 less
// question than expected.
// When the session is in `time` mode, the number of questions asked per session only matches up
// when FPS is five or less. Even five often gives one less question than expected. For example, if
// the session duration is 60 seconds, and a new question is asked every four seconds, we would
// expect exactly 15 questions to be asked per session if we just let it run without answering any
// of the questions. Instead, 14 questions are being asked in a session.
const FPS = 60;
const FRAME_TIME_MS = 1000 / FPS;
// TO-DO list:
// 1. Finish organizing functions, start using SessionLength, and give code a general once-over.
// 2. Make layout look good on literally ANY screen size.
// 3. Allow user to enter answer regardless of whether the answer box is focused or not?
// 4. Add a "settings" button that opens a modal with all the settings?
// 5. Make flash durations scale with answer time limit. Maybe clamped?
// 6. Add some kind of visual indicator at session finish, kinda like answer flashes?
// 7. Figure out this weird framerate thing.
// 8. Add hotkey for pausing (perhaps the space key).
// 9. Add an option to use the mobile keyboard instead of the numpad.
// 10. See if it's possible to make the mobile keyboard appear as a numpad instead of a regular
// keyboard.
// Current mobile issues:
// 1. The settings secton is too wide for the screen, so the input boxes cut off their contents.
// 2. Pressing "Start", or tapping any of the numpad buttons while the session is runnning, causes
// the mobile keyboard to appear.
// 3. Zooming in and then scrolling causes the numpad to resize or even disappear, and it doesn't
// always reappear or go back to its proper size even when the zoom level is returned to normal.
export default class GameUI {
constructor() {
this.game = new Game({
onStartQuestionCallback: () => this.onStartQuestion(),
onEndQuestionCallback: () => this.onEndQuestion(),
onFinishCallback: () => this.onFinish(),
answerTimeLimit: this.getAnswerTimeLimit(),
factor1Min: this.getFactor1Min(),
factor1Max: this.getFactor1Max(),
factor2Min: this.getFactor2Min(),
factor2Max: this.getFactor2Max(),
sessionLengthType: this.getSessionLengthType(),
sessionLength: this.getSessionLength(),
});
this.gameLoopInterval = null;
}
keepFocus() {
if (document.activeElement !== ANSWER) {
ANSWER.focus();
}
}
onStartQuestion() {
this.updateScoreDisplay();
this.updateQuestionDisplay();
this.clearAnswerBox();
}
onEndQuestion() {
this.processQuestionIncorrect();
}
/* {{{ ********** INITIALIZATION ********** */
init() {
// ANSWER.focus();
this.registerEventListeners();
this.updateGameFromUIInputs();
this.updateUIOutputsFromGame();
}
registerEventListeners() {
ANSWER_TIME_LIMIT.addEventListener("input", () => this.updateAnswerTimeLimit());
FACTOR_1_MIN.addEventListener("input", () => this.updateFactor1Min());
FACTOR_1_MAX.addEventListener("input", () => this.updateFactor1Max());
FACTOR_2_MIN.addEventListener("input", () => this.updateFactor2Min());
FACTOR_2_MAX.addEventListener("input", () => this.updateFactor2Max());
SESSION_LENGTH_TYPE.forEach((radio) => {
radio.addEventListener("change", () => {
this.updateSessionLengthType();
this.updateSessionLength();
});
});
// TODO: Only update session length if it's currently in time mode.
SESSION_LENGTH_TIME.addEventListener("input", () => this.updateSessionLength());
// TODO: Only update session length if it's currently in count mode.
SESSION_LENGTH_COUNT.addEventListener("input", () => this.updateSessionLength());
ANSWER.addEventListener("input", () => this.sendAnswerIfCorrectLength());
ANSWER.addEventListener("blur", () => this.keepFocus());
window.addEventListener("click", () => this.keepFocus());
window.addEventListener("focus", () => this.keepFocus());
PAUSE_RESUME.addEventListener("click", () => this.togglePause());
RESET.addEventListener("click", () => this.reset());
NUMPAD_BUTTONS.forEach((button) => {
button.addEventListener("click", () => {
const buttonValue = button.textContent;
if (buttonValue === "C") {
this.clearAnswerBox();
} else if (buttonValue === "←") {
this.deleteLastFromAnswerBox();
} else {
this.inputNumberToAnswerBox(buttonValue);
}
});
});
}
/* }}} */
/* {{{ ********** UPDATE GAME WITH UI ********** */
updateGameFromUIInputs() {
this.updateAnswerTimeLimit();
this.updateFactor1Min();
this.updateFactor1Max();
this.updateFactor2Min();
this.updateFactor2Max();
this.updateSessionLengthType();
this.updateSessionLength();
}
updateAnswerTimeLimit() {
this.game.setAnswerTimeLimit(this.getAnswerTimeLimit());
}
updateFactor1Min() {
this.game.setFactor1Min(this.getFactor1Min());
}
updateFactor1Max() {
this.game.setFactor1Max(this.getFactor1Max());
}
updateFactor2Min() {
this.game.setFactor2Min(this.getFactor2Min());
}
updateFactor2Max() {
this.game.setFactor2Max(this.getFactor2Max());
}
updateSessionLengthType() {
this.game.setSessionLengthType(this.getSessionLengthType());
}
updateSessionLength() {
this.game.setSessionLength(this.getSessionLength());
}
/* }}} */
/* {{{ ********** GET CURRENT UI STATE ********** */
getAnswerTimeLimit() {
return parseFloat(ANSWER_TIME_LIMIT.value) * 1000;
}
getFactor1Min() {
return parseInt(FACTOR_1_MIN.value);
}
getFactor1Max() {
return parseInt(FACTOR_1_MAX.value);
}
getFactor2Min() {
return parseInt(FACTOR_2_MIN.value);
}
getFactor2Max() {
return parseInt(FACTOR_2_MAX.value);
}
getSessionLengthType() {
return document.querySelector('input[name="session-length-type"]:checked').value;
}
getSessionLength() {
if (this.getSessionLengthType() === "time") {
return parseFloat(SESSION_LENGTH_TIME.value) * 60 * 1000;
} else {
return parseInt(SESSION_LENGTH_COUNT.value);
}
}
/* }}} */
/* {{{ ********** UPDATE UI WITH GAME ********** */
updateUIOutputsFromGame() {
this.updateSessionTimerDisplay();
this.updateScoreDisplay();
this.updateAnswerTimerDisplay();
this.updateQuestionDisplay();
}
updateSessionTimerDisplay() {
this.setSessionTimerDisplay(this.game.getSessionTimerProgress());
}
updateScoreDisplay() {
SCORE.textContent = `${this.game.getNumQuestionsCorrect()} / ${this.game.getNumQuestionsAsked()}`;
}
updateAnswerTimerDisplay() {
this.setAnswerTimerDisplay(this.game.getAnswerTimerProgress());
}
updateQuestionDisplay() {
if (this.game.getIsPaused()) {
QUESTION.textContent = "Paused";
} else {
QUESTION.textContent = `${this.game.getFactor1()} x ${this.game.getFactor2()}`;
}
}
/* }}} */
/* {{{ ********** LOGIC ********** */
// The only reason we have a main loop (instead of everything being purely event-driven) is to
// update the timers, their displays, and the logic that needs to be executed when they expire.
startGameLoopInterval() {
this.gameLoopInterval = setInterval(() => this.tick(), FRAME_TIME_MS);
}
tick() {
this.game.tick();
this.updateSessionTimerDisplay();
this.updateAnswerTimerDisplay();
}
sendAnswerIfCorrectLength() {
if (ANSWER.value.length === this.game.getCorrectAnswer().toString().length) {
if (this.game.receiveAnswer(parseInt(ANSWER.value))) {
this.processQuestionCorrect();
} else {
this.processQuestionIncorrect();
}
this.clearAnswerBox();
}
}
// Progress is a number on the range [0, 1].
setSessionTimerDisplay(progress) {
SESSION_TIMER_DISPLAY.style.width = `${progress * 100}%`;
}
// Progress is a number on the range [0, 1].
setAnswerTimerDisplay(progress) {
let ang = progress * 360;
ANSWER_TIMER_DISPLAY.style.background = `conic-gradient(#4CAF50 ${ang}deg, #333 ${ang}deg)`;
}
processQuestionCorrect() {
this.flashElement("answer", "#00ff00", 250, "transparent");
}
processQuestionIncorrect() {
this.flashElement("answer", "#ff0000", 250, "transparent");
}
start() {
PAUSE_RESUME.textContent = "Pause";
ANSWER.disabled = false;
this.disableSettings(true);
this.startGameLoopInterval();
this.game.start();
}
pause() {
this.game.pause();
// Comment this out to let `ANSWER_TIMER_DISPLAY` keep its current progress while paused, or
// uncomment it to instead reset it. Depends on preference. I kind of like seeing it stop
// where it is.
//
// this.updateAnswerTimerDisplay(0);
QUESTION.textContent = "Paused";
this.clearAnswerBox();
ANSWER.disabled = true;
this.disableSettings(false);
PAUSE_RESUME.textContent = "Resume";
clearInterval(this.gameLoopInterval);
}
onFinish() {
QUESTION.textContent = "Finished";
ANSWER.disabled = true;
PAUSE_RESUME.textContent = "Start";
PAUSE_RESUME.disabled = true;
clearInterval(this.gameLoopInterval);
}
reset() {
this.pause();
this.game.reset();
SCORE.textContent = "0 / 0";
this.setSessionTimerDisplay(0);
this.setAnswerTimerDisplay(0);
QUESTION.textContent = "Paused";
PAUSE_RESUME.textContent = "Start";
PAUSE_RESUME.disabled = false;
}
togglePause() {
this.game.getIsPaused() ? this.start() : this.pause();
}
flashElement(elementId, color, duration, originalColor) {
const element = document.getElementById(elementId);
if (!element) {
return;
}
element.style.backgroundColor = color;
setTimeout(() => (element.style.backgroundColor = originalColor), duration);
}
disableSettings(disabled) {
let containers = document.getElementsByClassName("settings");
Array.from(containers).forEach(function (container) {
let inputs = container.getElementsByTagName("input");
for (let i = 0; i < inputs.length; i++) {
inputs[i].disabled = disabled;
}
});
}
inputNumberToAnswerBox(num) {
if (this.game.getIsPaused()) {
return;
}
ANSWER.value += num;
this.sendAnswerIfCorrectLength();
}
clearAnswerBox() {
ANSWER.value = "";
}
deleteLastFromAnswerBox() {
ANSWER.value = ANSWER.value.slice(0, -1);
}
/* }}} */
}