-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
560 lines (487 loc) · 14.7 KB
/
app.js
File metadata and controls
560 lines (487 loc) · 14.7 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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
import {
GAME_SETTING,
RECENT_RECORDS_COUNT,
SHORT_PAUSE_TIME,
} from './config.js';
class KitchenTimerGameServer {
constructor() {
/** Variables */
this.levelSettings = GAME_SETTING;
this.recentRecordsCount = RECENT_RECORDS_COUNT;
this.shortPauseTime = SHORT_PAUSE_TIME;
this.allPlayersRecords = this.initAllPlayersRecords(); // functioning as a database
this.userName = this.initUserName();
this.userRecords = this.initUserRecords();
this.selectedLevel = 'easy';
this.targetTime = 0; // set in whole seconds, as humans typically count using whole numbers.
this.passedMillisecond = 0; // set in millisecond
this.timer = null;
this.timeout = null;
this.isGamePlaying = false;
this.isRunning = false;
/** Elements References */
this.app = document.getElementById('app');
this.userNameInput = document.getElementById('userName');
this.levelsCtn = document.getElementById('levelsCtn');
this.startBtn = document.getElementById('startBtn');
this.targetTimeCtn = document.getElementById('targetTimeCtn');
this.targetTimeCircle = document.getElementById('targetTimeCircle');
this.targetTimeDisplay = document.getElementById('targetTimeDisplay');
this.timerDisplay = document.getElementById('timerDisplay');
this.againBtn = document.getElementById('againBtn');
this.pauseToggleBtn = document.getElementById('pauseToggleBtn');
this.endBtn = document.getElementById('endBtn');
this.backBtn = document.getElementById('backBtn');
this.recordBtn = document.getElementById('recordBtn');
this.modal = document.getElementById('resultModal');
this.resultModalContent = document.getElementById('resultModalContent');
this.resultModalCloseBtn = document.getElementById('resultModalCloseBtn');
this.recordModalCloseBtn = document.getElementById('recordModalCloseBtn');
this.bestRecordDisplay = document.getElementById('bestRecordDisplay');
this.levelDetailsTableBody = document.getElementById(
'levelDetailsTableBody'
);
this.latestRecordsTableBody = document.getElementById(
'latestRecordsTableBody'
);
/** Initialization */
this.initLevelOptions();
this.initUserNameInput();
this.initStartBtn();
this.initEvents();
}
/** Helper Functions */
setDefaultRecord() {
const levelDetails = {};
// 動態生成 levelDetails
Object.keys(this.levelSettings).forEach((level) => {
levelDetails[level] = {
averageTime: null,
totalCount: 0,
compareToLastTime: 0,
};
});
const defaultRecord = {
bestRecord: null,
recentRecords: [],
levelDetails,
};
this.allPlayersRecords[this.userName] = defaultRecord;
this.saveAllPlayersRecords();
return defaultRecord;
}
saveUserName() {
localStorage.setItem('currentUserName', this.userName);
}
saveAllPlayersRecords() {
localStorage.setItem(
'allPlayersRecords',
JSON.stringify(this.allPlayersRecords)
);
}
initAllPlayersRecords() {
const records = localStorage.getItem('allPlayersRecords');
return records ? JSON.parse(records) : {};
}
initUserName() {
const name = localStorage.getItem('currentUserName');
return name ? name : '';
}
initUserRecords() {
if (!this.userName) return;
const pastRecords = this.allPlayersRecords[this.userName];
return pastRecords ? pastRecords : this.setDefaultRecord();
}
initLevelOptions() {
Object.keys(this.levelSettings).forEach((key, index) => {
const setting = this.levelSettings[key];
const isChecked = index === 0 ? 'checked' : '';
this.levelsCtn.innerHTML += `
<button class="level" tabindex="0" data-key="${key}" data-level-name="${setting.levelName}">
<input type="radio" id="${key}" class="levelRadioInput" name="level" value="${key}" ${isChecked}>
<label for="${key}" class="levelRadioLabel"><span class="levelRadioButton"></span>${setting.levelName}</label>
</button>
`;
});
}
initUserNameInput() {
if (this.userName) {
this.userNameInput.value = this.userName;
}
}
initStartBtn() {
this.startBtn.disabled = this.userName ? false : true;
}
initEvents() {
this.userNameInput.addEventListener('input', () => {
this.enableStartBtn();
});
this.startBtn.addEventListener('click', () => {
this.startGame();
});
this.againBtn.addEventListener('click', () => {
this.isGamePlaying = true;
this.startGame();
});
this.pauseToggleBtn.addEventListener('click', () => {
this.toggleGamePause();
});
this.endBtn.addEventListener('click', () => {
this.endGame(false);
});
this.recordBtn.addEventListener('click', () => {
this.showPastRecords();
});
this.backBtn.addEventListener('click', () => {
this.backToPage1();
});
// 綁定 this 的作用域
this.handleKeydown = this.handleKeydown.bind(this);
}
/**
* Toggle the tab index of buttons on page 2 to -1.
* This prevents the buttons from being focused using the tab key.
*/
togglePage2ButtonTabIndex() {
const buttons = document.querySelectorAll('#page2 button');
buttons.forEach((button) => {
if (button.getAttribute('tabindex') === '-1') {
button.setAttribute('tabindex', '0');
} else {
button.setAttribute('tabindex', '-1');
}
});
}
getSelectedLevel() {
let level;
document.getElementsByName('level').forEach((radio) => {
if (radio.checked) {
level = radio.value;
}
});
return level;
}
enableStartBtn() {
this.selectedLevel = this.getSelectedLevel();
if (this.userNameInput.value.trim() && this.selectedLevel) {
this.startBtn.disabled = false;
} else {
this.startBtn.disabled = true;
}
}
getRandomIntTime(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
updateTimerDisplay() {
const totalSeconds = Math.floor(this.passedMillisecond / 1000);
const milliseconds = Math.floor(this.passedMillisecond % 1000);
const seconds = totalSeconds % 60;
const minutes = Math.floor(totalSeconds / 60);
/** 計時器單位顯示改成小 */
const MM = String(minutes).padStart(2, '0');
const SS = String(seconds).padStart(2, '0');
const ms = String(milliseconds).padStart(3, '0').slice(0, 2);
this.timerDisplay.textContent = `${MM}:${SS}.${ms}`;
// 加上遮罩遮擋計時器文字
if (this.passedMillisecond === 3000) {
this.targetTimeCtn.classList.add('mask');
}
}
startGame() {
// 檢查是否有選擇等級以及輸入使用者名稱
const level = this.getSelectedLevel();
const nameInputted = this.userNameInput.value.trim();
if (!nameInputted || level === undefined) {
alert('Please select a level & enter your name!');
return;
}
// 更新等級
this.selectedLevel = level;
// 畫面換頁
if (!this.isGamePlaying) {
this.app.classList.add('inPage2');
}
// 切換遊戲狀態
this.isGamePlaying = true;
// 移除開始按鈕焦點以避免重複點擊
this.startBtn.blur();
// 確認玩家
if (this.userName !== nameInputted) {
this.userName = nameInputted;
this.saveUserName();
}
if (!this.allPlayersRecords[this.userName]) {
this.userRecords = this.setDefaultRecord();
}
// 設定目標時間
const levelSettings = this.levelSettings[this.selectedLevel];
this.targetTime = this.getRandomIntTime(
levelSettings.minTargetTime,
levelSettings.maxTargetTime
);
this.targetTimeDisplay.textContent = `${this.targetTime}`;
// 重置計時器秒數
this.passedMillisecond = 0;
this.updateTimerDisplay();
// 重置按鈕狀態
this.togglePage2ButtonTabIndex();
this.endBtn.disabled = true;
this.pauseToggleBtn.disabled = true;
this.pauseToggleBtn.textContent = 'Pause';
// 清除任何存在的計時器&定時器,避免重複計時或加速計時
if (this.timer) {
clearInterval(this.timer);
}
if (this.timeout) {
clearTimeout(this.timeout);
}
// 短暫停頓後開始計時
this.timeout = setTimeout(() => {
this.runTimer();
clearTimeout();
}, this.shortPauseTime * 1000);
}
runTimer() {
// 開始計時
this.isRunning = true;
this.timer = setInterval(() => {
this.passedMillisecond += 10;
this.updateTimerDisplay();
}, 10); // 每 10 毫秒更新一次計時器顯示文字
// 更新按鈕狀態: ItsNow, Continue
this.endBtn.disabled = false;
this.pauseToggleBtn.disabled = false;
this.pauseToggleBtn.textContent = 'Pause';
// 讓計時器外環旋轉
this.targetTimeCircle.classList.add('rotate');
// 添加鍵盤按下事件
document.addEventListener('keydown', this.handleKeydown);
}
stopTimer(isEndGame) {
// 停止計時
this.isRunning = false;
clearInterval(this.timer);
// 更新按鈕狀態:Pause
this.endBtn.disabled = true;
if (isEndGame) {
this.pauseToggleBtn.disabled = true;
} else {
this.pauseToggleBtn.textContent = 'Continue';
}
// 讓計時器外環停止旋轉
this.targetTimeCircle.classList.remove('rotate');
}
toggleGamePause() {
if (!this.isGamePlaying) return;
if (this.isRunning) {
this.stopTimer(false);
this.targetTimeCtn.classList.add('mask-less');
} else {
this.runTimer();
this.targetTimeCtn.classList.remove('mask-less');
}
}
endGame(isBack) {
if (this.isRunning) {
this.isGamePlaying = false;
this.stopTimer(true);
this.saveUserRecord(isBack);
// 移除遮罩
this.targetTimeCtn.classList.remove('mask', 'mask-less');
}
}
backToPage1() {
this.endGame(true);
this.app.classList.toggle('inPage2');
this.togglePage2ButtonTabIndex();
// 移除遮罩
this.targetTimeCtn.classList.remove('mask', 'mask-less');
// 移除鍵盤按下事件
document.removeEventListener('keydown', this.handleKeydown);
}
handleKeydown(event) {
console.log(1, 'event', event);
if (event.shiftKey) {
if (event.code === 'KeyS') {
this.toggleGamePause();
} else if (event.code === 'KeyQ') {
this.backToPage1();
}
} else if (event.code === 'Space') {
this.endGame();
}
}
saveUserRecord(isBack) {
if (isBack) {
return;
}
const difference = (this.passedMillisecond - this.targetTime * 1000) / 1000;
// 更新最佳紀錄
if (
!this.userRecords.bestRecord ||
Math.abs(difference) < Math.abs(this.userRecords.bestRecord)
) {
this.userRecords.bestRecord = difference;
}
// 更新最近紀錄
this.userRecords.recentRecords.push({
time: difference,
level: this.selectedLevel,
});
if (this.userRecords.recentRecords.length > this.recentRecordsCount) {
this.userRecords.recentRecords.shift();
}
// 更新等級紀錄
const levelData = this.userRecords.levelDetails[this.selectedLevel];
const pastAverageTime = levelData.averageTime ?? 0;
const newTotalCount = levelData.totalCount + 1;
const newAverageTime =
(pastAverageTime * (newTotalCount - 1) + difference) / newTotalCount;
const compareToLastTime =
levelData.averageTime === null ? 0 : difference - levelData.averageTime;
const newData = {
averageTime: newAverageTime,
totalCount: newTotalCount,
compareToLastTime: compareToLastTime,
};
this.userRecords.levelDetails[this.selectedLevel] = newData;
// 更新資料庫
this.allPlayersRecords[this.userName] = this.userRecords;
this.saveAllPlayersRecords();
// 顯示結果互動視窗
this.showFinalResult(difference);
}
async showFinalResult(difference) {
const differenceText =
difference === 0
? '±0.00'
: `${difference > 0 ? '+' : ''}${difference.toFixed(2)}`;
this.resultModalContent.textContent = `Result: ${differenceText} seconds`;
// 顯示結果互動視窗
const modal = new bootstrap.Modal('#resultModal');
modal.show();
// 自動聚焦在關閉按鈕上
document.getElementById('resultModal').addEventListener(
'shown.bs.modal',
() => {
this.resultModalCloseBtn.focus();
},
{ once: true }
);
}
showPastRecords() {
console.log(1, 'this.selectedLevel', this.selectedLevel);
const bestRecord = this.userRecords.bestRecord;
const levelDetails = this.userRecords.levelDetails;
const recentRecords = this.userRecords.recentRecords;
// 顯示最佳紀錄
this.bestRecordDisplay.textContent = bestRecord ?? '-';
// 顯示各等級紀錄
let levelDetailsRawHTML = '';
for (const level in levelDetails) {
const { averageTime, totalCount, compareToLastTime } =
levelDetails[level];
if (averageTime === null) {
levelDetailsRawHTML += `
<tr>
<th>${level}</th>
<td>-</td>
<td>-</td>
</tr>
`;
} else {
let compareIcon = '';
if (level === this.selectedLevel) {
compareIcon =
compareToLastTime == 0
? '<i class="bi bi-arrows"></i>'
: compareToLastTime > 0
? '<i class="bi bi-caret-up-fill"></i>'
: '<i class="bi bi-caret-down-fill"></i>';
}
levelDetailsRawHTML += `
<tr>
<th>${level}</th>
<td>
<span>${averageTime.toFixed(2)}</span>
<span>${compareIcon}</span>
</td>
<td>${totalCount}</td>
</tr>
`;
}
}
this.levelDetailsTableBody.innerHTML = levelDetailsRawHTML;
// 顯示最近紀錄
let recentRecordsRawHTML = '';
const recentRecordsCount = recentRecords.length;
if (recentRecordsCount) {
let order = 1;
for (let i = recentRecordsCount - 1; i >= 0; i--) {
const { time, level } = recentRecords[i];
recentRecordsRawHTML += `
<tr>
<th>${order}</th>
<td>${time.toFixed(2)}</td>
<td>${level}</td>
</tr>
`;
order++;
}
} else {
recentRecordsRawHTML = `
<tr>
<th>-</th>
<td>-</td>
<td>-</td>
</tr>
`;
}
this.latestRecordsTableBody.innerHTML = recentRecordsRawHTML;
const modal = new bootstrap.Modal('#recordModal');
modal.show();
// 自動聚焦在關閉按鈕上
document.getElementById('recordModal').addEventListener(
'shown.bs.modal',
() => {
this.recordModalCloseBtn.focus();
},
{ once: true }
);
}
}
// 待網頁載入後啟動遊戲
document.addEventListener('DOMContentLoaded', () => {
const game = new KitchenTimerGameServer();
// Select level by clicking keyboard 'Enter' or 'Space'
document.querySelectorAll('.level').forEach((button) => {
button.addEventListener('keydown', (event) => {
if (event.code === 'Enter' || event.code === 'Space') {
const radioInput = button.querySelector('.levelRadioInput');
if (radioInput) {
radioInput.checked = true;
}
}
});
});
// Auto-focus on name field if not filled
const userNameInput = document.getElementById('userName');
if (!userNameInput.value) {
userNameInput.focus();
}
// Avoid selecting buttons in page2 by click tab key
game.togglePage2ButtonTabIndex();
// Auto start/restart game by pressing 'Shift + A'
document.addEventListener('keydown', (event) => {
console.log(0, 'event', event);
if (event.shiftKey && event.code === 'KeyA') {
if (game.isGamePlaying) {
// 遊戲中重來的話就移除遮罩
game.targetTimeCtn.classList.remove('mask', 'mask-less');
// 遊戲中重來的話就讓計時器外環停止旋轉
game.targetTimeCircle.classList.remove('rotate');
}
game.startGame();
}
});
});