-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquiz.ts
More file actions
581 lines (510 loc) · 15.2 KB
/
Copy pathquiz.ts
File metadata and controls
581 lines (510 loc) · 15.2 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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
// model
interface Question {
questionText: string;
choices: string[];
correctAnswer: string;
playerAnswer: string | null;
}
type Result = "correct" | "wrong" | "empty";
interface QuestionResult {
question: Question;
result: Result;
}
type PlayingState = "waiting for questions" | "playing" | "finished";
// enum PlayingState {
// "not started",
// "playing",
// "finished",
// }
class QuizGame {
private questions: Question[];
private currentQuestion: Question | null;
private score: number;
private playingState: PlayingState;
constructor() {
this.questions = [];
this.currentQuestion = null;
this.score = 0;
this.playingState = "waiting for questions";
}
public startGame(questions: Question[]): void {
switch (this.playingState) {
case "waiting for questions":
if (!questions.length) {
throw new Error("No questions were provided");
}
this.questions = questions;
this.currentQuestion = this.questions[0];
this.playingState = "playing";
break;
default:
break;
}
}
public endGame(): void {
switch (this.playingState) {
case "playing":
this.playingState = "finished";
break;
default:
break;
}
}
private nextQuestion(): Question | null {
if (!this.currentQuestion) {
throw new Error("No more questions left");
}
const index = this.questions.indexOf(this.currentQuestion);
return index + 1 >= this.questions.length
? null
: this.questions[index + 1];
}
public submitAnswer(answer: string): void {
if (!this.currentQuestion) {
throw new Error("Can't submit null question");
}
if (!this.currentQuestion.choices.includes(answer)) {
throw new Error("Invalid answer");
}
this.currentQuestion.playerAnswer = answer;
if (
this.currentQuestion.correctAnswer === this.currentQuestion.playerAnswer
) {
this.score += 1;
}
}
public advanceQuestion(): void {
this.currentQuestion = this.nextQuestion();
if (!this.currentQuestion) {
this.endGame();
}
}
public getCurrentQuestion(): Question | null {
return this.currentQuestion;
}
public getPlayingState(): PlayingState {
return this.playingState;
}
public getScore(): number {
return this.score;
}
public getQuestions(): Question[] {
return this.questions;
}
}
function addClass(classToBeAdded: string, currentClass: string): string {
const classes = currentClass.split(" ");
if (classes.includes(classToBeAdded)) {
return currentClass;
}
return `${currentClass} ${classToBeAdded}`;
}
function removeClass(classToBeRemoved: string, currentClass: string): string {
const classes = currentClass.split(" ");
if (!classes.includes(classToBeRemoved)) {
return currentClass;
}
classes.splice(classes.indexOf(classToBeRemoved), 1);
return classes.join(" ");
}
// view
interface eventListenerMap {
choices?: Function;
nextQuestion?: Function;
playAgain?: Function;
}
class View {
private questionText: HTMLElement;
private choices: HTMLElement[];
private gameOver: HTMLElement;
private score: HTMLElement;
private nextQuestion: HTMLElement;
private loading: HTMLElement;
private question: HTMLElement;
private playAgain: HTMLElement;
private progress: HTMLElement | null;
public progressDots: HTMLElement[];
constructor() {
this.questionText = document.querySelector(".question-text") as HTMLElement;
this.choices = [0, 1, 2, 3]
.map((index) => "#choice-" + index.toString())
.map((id) => document.querySelector(id) as HTMLElement);
this.gameOver = document.querySelector(".game-over") as HTMLElement;
this.score = document.querySelector(".score") as HTMLElement;
this.nextQuestion = document.querySelector(
".next-question-btn"
) as HTMLElement;
this.loading = document.querySelector(".loading") as HTMLElement;
this.question = document.querySelector(".question") as HTMLElement;
this.playAgain = document.querySelector(".play-again") as HTMLElement;
this.progress = null;
this.progressDots = [];
}
public displayQuestionText(text: string): void {
this.questionText.textContent = text;
}
public displayChoices(choiceArray: string[]): void {
this.choices.forEach((element, index) => {
element.textContent = choiceArray[index];
});
}
public displayScore(score: number): void {
this.score.textContent = score.toString();
}
public hideProgress(): void {
this.progress?.setAttribute("hidden", "true");
}
public hideProgressDots(): void {
this.progressDots.forEach((dot) => dot.setAttribute("hidden", "true"));
}
public displayProgress(currentQuestionIndex: number): void {
this.progressDots.forEach((dot, index) => {
if (index < currentQuestionIndex) {
dot.setAttribute("class", addClass("progressed", dot.className));
} else {
dot.setAttribute("class", removeClass("progressed", dot.className));
}
});
}
public initializeProgress(questionAmount: number): void {
this.progress = document.createElement("div");
this.progress.setAttribute("class", "progress");
for (let index = 0; index < questionAmount; index += 1) {
const dot = document.createElement("div");
dot.textContent = "•";
dot.setAttribute("class", "dot");
this.progressDots.push(dot);
this.progress.appendChild(dot);
}
document.body.appendChild(this.progress);
}
public hideLoading(): void {
this.loading.setAttribute("hidden", "true");
}
public exposeLoading(): void {
this.loading.removeAttribute("hidden");
}
public hideQuestionText(): void {
this.questionText.setAttribute("hidden", "true");
}
public hideChoices(): void {
this.choices.forEach((c) => c.setAttribute("hidden", "true"));
}
public hideQuestion(): void {
this.question.setAttribute("hidden", "true");
}
public exposeQuestionText(): void {
this.questionText.removeAttribute("hidden");
}
public exposeChoices(): void {
this.choices.forEach((c) => c.removeAttribute("hidden"));
}
public exposeQuestion(): void {
this.question.removeAttribute("hidden");
}
public hideGameOver(): void {
this.gameOver.setAttribute("hidden", "true");
}
public exposeGameOver(): void {
this.gameOver.removeAttribute("hidden");
}
public exposeNextQuestion(): void {
this.nextQuestion.setAttribute(
"class",
addClass("visible", this.nextQuestion.className)
);
}
public hideNextQuestion(): void {
this.nextQuestion.setAttribute(
"class",
removeClass("visible", this.nextQuestion.className)
);
}
public gameOverScreen(): void {
this.hideQuestion();
this.hideNextQuestion();
this.exposeGameOver();
}
public highlightCorrectAnswer(elementIndex: number): void {
const element = this.choices[elementIndex];
element.setAttribute(
"class",
addClass("correct-answer", element.className)
);
}
public dehighlightCorrectAnswer(): void {
this.choices.forEach((choiceElement) => {
choiceElement.setAttribute(
"class",
removeClass("correct-answer", choiceElement.className)
);
});
}
public highlightPlayerAnswerAsCorrect(elementIndex: number): void {
const element = this.choices[elementIndex];
element.setAttribute(
"class",
addClass("correct-player-answer", element.className)
);
}
public highlightPlayerAnswerAsWrong(elementIndex: number): void {
const element = this.choices[elementIndex];
element.setAttribute(
"class",
addClass("wrong-player-answer", element.className)
);
}
public dehighlightPlayerAnswer(): void {
this.choices.forEach((choiceElement) => {
choiceElement.setAttribute(
"class",
removeClass("wrong-player-answer", choiceElement.className)
);
choiceElement.setAttribute(
"class",
removeClass("correct-player-answer", choiceElement.className)
);
});
}
public addEventListeners(
eventListeners: eventListenerMap,
context: unknown
): void {
Object.entries(eventListeners).forEach((entry) => {
const [elementName, callback] = entry;
switch (elementName) {
case "choices":
this.choices.forEach((choiceElement) => {
choiceElement.addEventListener("click", callback.bind(context));
});
break;
case "nextQuestion":
this.nextQuestion.addEventListener("click", callback.bind(context));
break;
case "playAgain":
this.playAgain.addEventListener("click", callback.bind(context));
break;
default:
throw new Error("invalid key");
break;
}
});
}
}
class Presenter {
private game: QuizGame;
private view: View;
private placeholderQuestions: Question[];
constructor(game: QuizGame, view: View) {
this.game = game;
this.view = view;
this.placeholderQuestions = [
{
questionText: "Which's the tallest mountain in the world?",
playerAnswer: null,
choices: [
"Mountain Everest",
"Matterhorn",
"Mount Kilimanjaro",
"Mount Fuji",
],
correctAnswer: "Mountain Everest",
},
{
questionText:
"Who's the actress that played Jane Smith in the movie Mr. & Mrs. Smith?",
playerAnswer: null,
choices: [
"Helena Bonham Carter",
"Reese Witherspoon",
"Angelina Jolie",
"Sandra Bullock",
],
correctAnswer: "Angelina Jolie",
},
{
questionText: "Who's the singer of the song Smooth Criminal?",
playerAnswer: null,
choices: ["Michael Jackson", "Madonna", "Mariah Carey", "Garth Brooks"],
correctAnswer: "Michael Jackson",
},
{
questionText:
"Who's the Serbian-American inventor known for his contributions to alternating current?",
playerAnswer: null,
choices: [
"Henry Ford",
"Nikola Tesla",
"Alexander Graham Bell",
"Steve Jobs",
],
correctAnswer: "Nikola Tesla",
},
{
questionText:
"Who's the Greek philosopher who wrote the Legend of Atlantis?",
playerAnswer: null,
choices: ["Plato", "Sun Tzu", "Bobby Hill", "Ibn Sina"],
correctAnswer: "Plato",
},
];
this.initializeEventListeners();
game.startGame(this.placeholderQuestions);
this.renderAll();
// this.getQuestionsAndStartGame();
}
private renderAll(): void {
this.renderLoading();
this.renderProgressDots();
this.renderQuestionText();
this.renderChoices();
this.renderScore();
this.renderPlayerAnswerAndCorrectAnswer();
this.renderNextQuestionBtn();
this.renderGameOverScreen();
}
private renderLoading(): void {
if (this.game.getPlayingState() === "waiting for questions") {
this.view.exposeLoading();
this.view.hideQuestion();
return;
}
this.view.hideLoading();
this.view.exposeQuestion();
}
private renderProgressDots(): void {
if (this.game.getPlayingState() === "playing") {
if (!this.view.progressDots.length) {
this.view.initializeProgress(this.game.getQuestions().length);
}
const currentQuestion = this.game.getCurrentQuestion();
if (!currentQuestion) {
throw new Error("Current question must not be null");
}
this.view.displayProgress(
this.game.getQuestions().indexOf(currentQuestion)
);
return;
}
this.view.hideProgress();
}
private renderGameOverScreen(): void {
if (this.game.getPlayingState() === "finished") {
this.view.gameOverScreen();
}
}
private renderNextQuestionBtn(): void {
const currentQuestion = this.game.getCurrentQuestion();
if (!currentQuestion) {
return;
}
if (currentQuestion.playerAnswer === null) {
this.view.hideNextQuestion();
return;
}
this.view.exposeNextQuestion();
}
private renderQuestionText(): void {
const currentQuestion = this.game.getCurrentQuestion();
if (!currentQuestion) {
console.log("no current question");
return;
}
this.view.displayQuestionText(currentQuestion.questionText);
}
private renderChoices(): void {
const currentQuestion = this.game.getCurrentQuestion();
if (!currentQuestion) {
console.log("no current question");
return;
}
this.view.displayChoices(currentQuestion.choices);
}
private renderScore(): void {
this.view.displayScore(this.game.getScore());
}
private renderPlayerAnswerAndCorrectAnswer(): void {
const currentQuestion = this.game.getCurrentQuestion();
if (!currentQuestion) {
return;
}
if (currentQuestion.playerAnswer === null) {
this.view.dehighlightCorrectAnswer();
this.view.dehighlightPlayerAnswer();
return;
}
const playerAnwserIndex = this.getChoiceIndex(currentQuestion.playerAnswer);
const correctAnwserIndex = this.getChoiceIndex(
currentQuestion.correctAnswer
);
this.view.highlightCorrectAnswer(correctAnwserIndex);
if (currentQuestion.correctAnswer === currentQuestion.playerAnswer) {
this.view.highlightPlayerAnswerAsCorrect(playerAnwserIndex);
} else {
this.view.highlightPlayerAnswerAsWrong(playerAnwserIndex);
}
}
private getChoiceIndex(choice: string): number {
const choices = this.game.getCurrentQuestion()?.choices;
const index = choices?.indexOf(choice);
if (index === undefined) {
throw new Error("Invalid choice");
}
return index;
}
private initializeEventListeners(): void {
this.view.addEventListeners(
{
choices: this.choiceCallback,
nextQuestion: this.nextQuestionCallback,
playAgain: this.playAgainCallback,
},
this
);
}
private nextQuestionCallback(): void {
this.game.advanceQuestion();
this.renderAll();
}
private playAgainCallback(): void {
location.reload();
}
private choiceCallback(event: MouseEvent): void {
const currentQuestion = this.game.getCurrentQuestion();
if (!currentQuestion) {
return;
}
if (currentQuestion.playerAnswer !== null) {
return;
}
const target = event.target as HTMLElement;
const answer = target.textContent ?? "";
this.game.submitAnswer(answer);
if (this.game.getPlayingState() === "finished") {
this.view.gameOverScreen();
}
this.renderAll();
}
public async getQuestionsAndStartGame() {
const response = await fetch("insert api url");
const questionsData = await response.json();
const questions = questionsData.map((question): Question => {
const randomIndex = Math.floor(
Math.random() * question.incorrectAnswers.length
);
const choices = question.incorrectAnswers;
choices.splice(randomIndex, 0, question.correctAnswer);
return {
questionText: question.question.text,
choices: choices,
playerAnswer: null,
correctAnswer: question.correctAnswer,
};
});
game.startGame(questions);
this.renderAll();
}
}
const game = new QuizGame();
const view = new View();
const presenter = new Presenter(game, view);