-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrivia_app_demo.ts
More file actions
531 lines (449 loc) · 14.6 KB
/
trivia_app_demo.ts
File metadata and controls
531 lines (449 loc) · 14.6 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
/**
* Trivia Q&A Application - Demo Version (TypeScript)
*
* Uses mock data to demonstrate the application flow without requiring network access.
* Run with: npm run build && node dist/trivia_app_demo.js
* Or with ts-node: ts-node trivia_app_demo.ts
*/
import * as readline from "readline";
// ============================================================================
// Configuration & Constants
// ============================================================================
const API_ENDPOINT = "https://opentdb.com/api.php?amount=10";
// ============================================================================
// Logging Configuration
// ============================================================================
enum LogLevel {
DEBUG = 0,
INFO = 1,
WARNING = 2,
ERROR = 3,
}
class Logger {
private level: LogLevel;
private name: string;
constructor(name: string, level: LogLevel = LogLevel.INFO) {
this.name = name;
this.level = level;
}
private formatMessage(logLevel: LogLevel, message: string): string {
const timestamp = new Date().toISOString();
const levelName = LogLevel[logLevel];
return `${timestamp} - ${this.name} - ${levelName} - ${message}`;
}
debug(message: string): void {
if (this.level <= LogLevel.DEBUG) {
console.log(this.formatMessage(LogLevel.DEBUG, message));
}
}
info(message: string): void {
if (this.level <= LogLevel.INFO) {
console.log(this.formatMessage(LogLevel.INFO, message));
}
}
warning(message: string): void {
if (this.level <= LogLevel.WARNING) {
console.log(this.formatMessage(LogLevel.WARNING, message));
}
}
error(message: string, error?: Error): void {
if (this.level <= LogLevel.ERROR) {
const errorMessage = error ? `${message}\n${error.stack}` : message;
console.error(this.formatMessage(LogLevel.ERROR, errorMessage));
}
}
}
const logger = new Logger("trivia_app", LogLevel.INFO);
// ============================================================================
// Domain Models
// ============================================================================
interface TriviaQuestion {
category: string;
difficulty: string;
question: string;
correct_answer: string;
incorrect_answers: string[];
}
interface TriviaResponseData {
response_code: number;
results: TriviaQuestion[];
}
class Question {
private category: string;
private difficulty: string;
private question: string;
private correctAnswer: string;
private incorrectAnswers: string[];
constructor(data: TriviaQuestion) {
this.category = this.decodeHtmlEntities(data.category);
this.difficulty = data.difficulty;
this.question = this.decodeHtmlEntities(data.question);
this.correctAnswer = this.decodeHtmlEntities(data.correct_answer);
this.incorrectAnswers = data.incorrect_answers.map((ans) =>
this.decodeHtmlEntities(ans)
);
}
private decodeHtmlEntities(text: string): string {
const htmlEntities: Record<string, string> = {
"&": "&",
"<": "<",
">": ">",
""": '"',
"'": "'",
"'": "'",
};
return text.replace(/&[a-zA-Z]+;/g, (entity) => htmlEntities[entity] || entity);
}
getCategory(): string {
return this.category;
}
getDifficulty(): string {
return this.difficulty;
}
getQuestion(): string {
return this.question;
}
getCorrectAnswer(): string {
return this.correctAnswer;
}
getAllAnswers(): string[] {
const answers = [...this.incorrectAnswers, this.correctAnswer];
return this.shuffle(answers);
}
private shuffle<T>(array: T[]): T[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
}
class TriviaResponse {
private responseCode: number;
private results: Question[];
constructor(data: TriviaResponseData) {
this.responseCode = data.response_code;
this.results = data.results.map((item) => new Question(item));
}
getResponseCode(): number {
return this.responseCode;
}
getResults(): Question[] {
return this.results;
}
}
// ============================================================================
// Mock Data Provider
// ============================================================================
class MockTriviaProvider {
static getMockData(): TriviaResponse {
const mockResults: TriviaQuestion[] = [
{
category: "Entertainment: Comics",
difficulty: "hard",
question:
"Better known by his nickname Logan, what is Wolverine's birth name?",
correct_answer: "James Howlett",
incorrect_answers: ["Logan Wolf", "Thomas Wilde", "John Savage"],
},
{
category: "History",
difficulty: "easy",
question:
"Which one of these countries was NOT in the Central Powers during WWI?",
correct_answer: "Spain",
incorrect_answers: ["Austria-Hungary", "Turkey", "Germany"],
},
{
category: "Entertainment: Video Games",
difficulty: "easy",
question: 'When was "Luigi's Mansion 3" released?',
correct_answer: "October 31st, 2019",
incorrect_answers: [
"January 13th, 2019",
"September 6th, 2018",
"October 1st, 2019",
],
},
{
category: "General Knowledge",
difficulty: "easy",
question: "Earth is located in which galaxy?",
correct_answer: "The Milky Way Galaxy",
incorrect_answers: ["The Mars Galaxy", "The Galaxy Note", "The Black Hole"],
},
{
category: "Science: Gadgets",
difficulty: "medium",
question:
"In what year was the Oculus Rift revealed to the public through a Kickstarter campaign?",
correct_answer: "2012",
incorrect_answers: ["2010", "2011", "2013"],
},
{
category: "Entertainment: Books",
difficulty: "easy",
question: 'Who wrote "A Tale of Two Cities"?',
correct_answer: "Charles Dickens",
incorrect_answers: ["Charles Darwin", "Mark Twain", "Roald Dahl"],
},
{
category: "Entertainment: Japanese Anime & Manga",
difficulty: "medium",
question:
'Which of the stands from "JoJo's Bizarre Adventure" mimics the likeness of a tomato?',
correct_answer: "Pearl Jam",
incorrect_answers: [
"Red Hot Chili Pepper",
"Cream Starter",
"Nut King Call",
],
},
{
category: "Entertainment: Video Games",
difficulty: "medium",
question:
"How many times do you fight the Imprisoned in The Legend of Zelda: Skyward Sword?",
correct_answer: "3",
incorrect_answers: ["2", "4", "5"],
},
{
category: "Science: Computers",
difficulty: "medium",
question: "What does the term MIME stand for, in regards to computing?",
correct_answer: "Multipurpose Internet Mail Extensions",
incorrect_answers: [
"Mail Internet Mail Exchange",
"Multipurpose Interleave Mail Exchange",
"Mail Interleave Method Exchange",
],
},
{
category: "Entertainment: Video Games",
difficulty: "hard",
question:
"In Diablo lore, this lesser evil spawned from one of the seven heads of Tathamet, and was known as the Maiden of Anguish.",
correct_answer: "Andariel",
incorrect_answers: ["Valla", "Malthael", "Kashya"],
},
];
const responseData: TriviaResponseData = {
response_code: 0,
results: mockResults,
};
return new TriviaResponse(responseData);
}
}
// ============================================================================
// Trivia Game
// ============================================================================
interface AnswerRecord {
question: string;
selected: string;
correct: string;
isCorrect: boolean;
}
class TriviaGame {
private questions: Question[];
private currentQuestionIndex: number = 0;
private score: number = 0;
private answersGiven: AnswerRecord[] = [];
constructor(questions: Question[]) {
this.questions = questions;
}
getCurrentQuestion(): Question | null {
if (this.currentQuestionIndex < this.questions.length) {
return this.questions[this.currentQuestionIndex];
}
return null;
}
submitAnswer(selectedAnswer: string): boolean {
const question = this.getCurrentQuestion();
if (!question) {
return false;
}
const isCorrect = selectedAnswer === question.getCorrectAnswer();
this.answersGiven.push({
question: question.getQuestion(),
selected: selectedAnswer,
correct: question.getCorrectAnswer(),
isCorrect,
});
if (isCorrect) {
this.score++;
logger.debug(`Correct answer. Score: ${this.score}/${this.answersGiven.length}`);
} else {
logger.debug(`Incorrect answer. Correct was: ${question.getCorrectAnswer()}`);
}
this.currentQuestionIndex++;
return isCorrect;
}
isGameOver(): boolean {
return this.currentQuestionIndex >= this.questions.length;
}
getScore(): number {
return this.score;
}
getQuestionCount(): number {
return this.questions.length;
}
getScorePercentage(): number {
if (this.answersGiven.length === 0) {
return 0;
}
return (this.score / this.answersGiven.length) * 100;
}
getAnswersGiven(): AnswerRecord[] {
return this.answersGiven;
}
}
// ============================================================================
// Console UI
// ============================================================================
class ConsoleUI {
private rl: readline.Interface;
constructor() {
this.rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
}
printHeader(text: string): void {
console.log("\n" + "=".repeat(80));
console.log(` ${text}`);
console.log("=".repeat(80));
}
printQuestion(
question: Question,
questionNumber: number,
total: number
): void {
console.log(`\n[Question ${questionNumber}/${total}]`);
console.log(`Category: ${question.getCategory()}`);
console.log(`Difficulty: ${question.getDifficulty().toUpperCase()}`);
console.log(`\n${question.getQuestion()}\n`);
}
printOptions(options: string[]): void {
options.forEach((option, index) => {
console.log(` ${index + 1}. ${option}`);
});
}
async getUserSelection(numOptions: number): Promise<number> {
return new Promise((resolve) => {
const askForInput = (): void => {
this.rl.question(
`\nYour answer (1-${numOptions}): `,
(input: string) => {
const selection = parseInt(input.trim(), 10);
if (isNaN(selection) || selection < 1 || selection > numOptions) {
console.log(
`Please enter a number between 1 and ${numOptions}`
);
askForInput();
return;
}
resolve(selection);
}
);
};
askForInput();
});
}
printAnswerFeedback(isCorrect: boolean, correctAnswer: string): void {
if (isCorrect) {
console.log("\n✓ CORRECT!");
} else {
console.log(`\n✗ INCORRECT. The correct answer was: ${correctAnswer}`);
}
}
printFinalScore(game: TriviaGame): void {
this.printHeader("GAME OVER - FINAL RESULTS");
console.log(
`\nTotal Score: ${game.getScore()}/${game.getQuestionCount()}`
);
console.log(`Percentage: ${game.getScorePercentage().toFixed(1)}%`);
console.log("\n" + "-".repeat(80));
console.log("Question Summary:\n");
game.getAnswersGiven().forEach((answer, index) => {
const status = answer.isCorrect ? "✓" : "✗";
console.log(`${index + 1}. ${status} ${answer.question}`);
console.log(` Your answer: ${answer.selected}`);
if (!answer.isCorrect) {
console.log(` Correct answer: ${answer.correct}`);
}
console.log();
});
}
async promptContinue(): Promise<void> {
return new Promise((resolve) => {
this.rl.question("\nPress Enter to continue to the next question...", () => {
resolve();
});
});
}
close(): void {
this.rl.close();
}
}
// ============================================================================
// Main Application (Demo)
// ============================================================================
async function main(): Promise<void> {
logger.info("Starting Trivia Q&A Application (DEMO MODE)");
const ui = new ConsoleUI();
try {
ui.printHeader("TRIVIA Q&A - OPEN TRIVIA DATABASE (DEMO)");
console.log("\nLoading trivia questions (using mock data for demo)...\n");
// Get mock data
const triviaResponse = MockTriviaProvider.getMockData();
const questions = triviaResponse.getResults();
if (!questions || questions.length === 0) {
console.log("\n✗ Failed to load trivia questions.");
logger.error("Application terminated due to data load failure");
ui.close();
return;
}
console.log(`✓ Loaded ${questions.length} questions\n`);
// Initialize game
const game = new TriviaGame(questions);
// Run game loop
while (!game.isGameOver()) {
const question = game.getCurrentQuestion();
if (!question) {
break;
}
const questionNumber = game.getAnswersGiven().length + 1;
const totalQuestions = game.getQuestionCount();
ui.printQuestion(question, questionNumber, totalQuestions);
const options = question.getAllAnswers();
ui.printOptions(options);
// Get user's answer
const selectionIndex = (await ui.getUserSelection(options.length)) - 1;
const selectedAnswer = options[selectionIndex];
// Check answer and provide feedback
const isCorrect = game.submitAnswer(selectedAnswer);
ui.printAnswerFeedback(isCorrect, question.getCorrectAnswer());
// Pause before next question
if (!game.isGameOver()) {
await ui.promptContinue();
}
}
// Display final results
ui.printFinalScore(game);
logger.info(
`Game completed. Final score: ${game.getScore()}/${game.getQuestionCount()}`
);
} catch (error) {
logger.error(
"Unexpected error during game",
error instanceof Error ? error : new Error(String(error))
);
console.log(
`\n✗ An unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`
);
} finally {
ui.close();
}
}
// Run the application
main();