forked from fbrcode/trivia-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrivia_app.cs
More file actions
563 lines (476 loc) · 16.8 KB
/
trivia_app.cs
File metadata and controls
563 lines (476 loc) · 16.8 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
/**
* Trivia Q&A Application (C#)
*
* A console-based trivia game that fetches questions from the Open Trivia Database API
* and provides an interactive Q&A experience with comprehensive logging and error handling.
*
* Design principles: Observability, Reliability, Resilience, Accuracy, Agility
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Web;
// ============================================================================
// Configuration & Constants
// ============================================================================
public static class Config
{
public const string API_ENDPOINT = "https://opentdb.com/api.php?amount=10";
public const int REQUEST_TIMEOUT = 10000; // milliseconds
public const int MAX_RETRIES = 3;
public const int RETRY_DELAY = 1000; // milliseconds
}
// ============================================================================
// Logging Configuration
// ============================================================================
public enum LogLevel
{
Debug = 0,
Info = 1,
Warning = 2,
Error = 3
}
public class Logger
{
private readonly string _name;
private readonly LogLevel _level;
public Logger(string name, LogLevel level = LogLevel.Info)
{
_name = name;
_level = level;
}
private string FormatMessage(LogLevel logLevel, string message)
{
string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
return $"{timestamp} - {_name} - {logLevel} - {message}";
}
public void Debug(string message)
{
if (_level <= LogLevel.Debug)
{
Console.Out.WriteLine(FormatMessage(LogLevel.Debug, message));
}
}
public void Info(string message)
{
if (_level <= LogLevel.Info)
{
Console.Out.WriteLine(FormatMessage(LogLevel.Info, message));
}
}
public void Warning(string message)
{
if (_level <= LogLevel.Warning)
{
Console.Out.WriteLine(FormatMessage(LogLevel.Warning, message));
}
}
public void Error(string message, Exception? exception = null)
{
if (_level <= LogLevel.Error)
{
string errorMessage = exception != null ? $"{message}\n{exception.StackTrace}" : message;
Console.Error.WriteLine(FormatMessage(LogLevel.Error, errorMessage));
}
}
}
private static readonly Logger Logger = new Logger("trivia_app", LogLevel.Info);
// ============================================================================
// Domain Models
// ============================================================================
public enum ResponseCode
{
Success = 0,
NoResults = 1,
InvalidParameter = 2,
TokenNotFound = 3,
TokenEmpty = 4
}
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true)]
public partial class TriviaQuestionDto
{
[JsonPropertyName("type")]
public string? Type { get; set; }
[JsonPropertyName("difficulty")]
public string? Difficulty { get; set; }
[JsonPropertyName("category")]
public string? Category { get; set; }
[JsonPropertyName("question")]
public string? Question { get; set; }
[JsonPropertyName("correct_answer")]
public string? CorrectAnswer { get; set; }
[JsonPropertyName("incorrect_answers")]
public List<string>? IncorrectAnswers { get; set; }
}
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true)]
public partial class TriviaResponseDto
{
[JsonPropertyName("response_code")]
public int ResponseCode { get; set; }
[JsonPropertyName("results")]
public List<TriviaQuestionDto>? Results { get; set; }
}
public class Question
{
public string Category { get; private set; }
public string Difficulty { get; private set; }
public string QuestionText { get; private set; }
public string CorrectAnswer { get; private set; }
public List<string> IncorrectAnswers { get; private set; }
public Question(TriviaQuestionDto dto)
{
Category = DecodeHtmlEntities(dto.Category ?? "Unknown");
Difficulty = dto.Difficulty ?? "unknown";
QuestionText = DecodeHtmlEntities(dto.Question ?? "");
CorrectAnswer = DecodeHtmlEntities(dto.CorrectAnswer ?? "");
IncorrectAnswers = (dto.IncorrectAnswers ?? new List<string>())
.Select(DecodeHtmlEntities)
.ToList();
}
private string DecodeHtmlEntities(string text)
{
if (string.IsNullOrEmpty(text))
return text;
return HttpUtility.HtmlDecode(text);
}
public List<string> GetAllAnswers()
{
var answers = new List<string>(IncorrectAnswers) { CorrectAnswer };
return Shuffle(answers);
}
private List<T> Shuffle<T>(List<T> list)
{
Random random = new Random();
for (int i = list.Count - 1; i > 0; i--)
{
int randomIndex = random.Next(i + 1);
(list[i], list[randomIndex]) = (list[randomIndex], list[i]);
}
return list;
}
}
public class TriviaResponse
{
public ResponseCode ResponseCode { get; private set; }
public List<Question> Results { get; private set; }
private TriviaResponse(ResponseCode responseCode, List<Question> results)
{
ResponseCode = responseCode;
Results = results;
}
public static TriviaResponse FromJson(TriviaResponseDto dto)
{
try
{
var responseCode = (ResponseCode)dto.ResponseCode;
if (responseCode != ResponseCode.Success)
{
throw new InvalidOperationException($"API returned error code: {responseCode}");
}
var results = (dto.Results ?? new List<TriviaQuestionDto>())
.Select(item => new Question(item))
.ToList();
return new TriviaResponse(responseCode, results);
}
catch (Exception ex)
{
Logger.Error("Failed to parse API response", ex);
throw new InvalidOperationException($"Invalid response format: {ex.Message}", ex);
}
}
}
// ============================================================================
// API Client (Resilience & Reliability)
// ============================================================================
public class TriviaAPIClient
{
private readonly string _endpoint;
private readonly int _timeout;
private readonly HttpClient _httpClient;
public TriviaAPIClient(
string endpoint = Config.API_ENDPOINT,
int timeout = Config.REQUEST_TIMEOUT)
{
_endpoint = endpoint;
_timeout = timeout;
_httpClient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(timeout) };
}
public async Task<TriviaResponse?> FetchQuestionsAsync()
{
for (int attempt = 1; attempt <= Config.MAX_RETRIES; attempt++)
{
try
{
Logger.Info($"Fetching questions from API (attempt {attempt}/{Config.MAX_RETRIES})");
var response = await _httpClient.GetAsync(_endpoint);
response.EnsureSuccessStatusCode();
Logger.Debug($"API response status: {response.StatusCode}");
var content = await response.Content.ReadAsStringAsync();
var jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var dto = JsonSerializer.Deserialize<TriviaResponseDto>(content, jsonOptions);
if (dto == null)
{
throw new InvalidOperationException("Failed to deserialize response");
}
var triviaResponse = TriviaResponse.FromJson(dto);
Logger.Info($"Successfully fetched {triviaResponse.Results.Count} questions");
return triviaResponse;
}
catch (HttpRequestException ex)
{
Logger.Warning($"Connection error on attempt {attempt}: {ex.Message}");
if (attempt < Config.MAX_RETRIES)
{
await Task.Delay(Config.RETRY_DELAY);
}
}
catch (TaskCanceledException)
{
Logger.Warning($"Request timeout on attempt {attempt}");
if (attempt < Config.MAX_RETRIES)
{
await Task.Delay(Config.RETRY_DELAY);
}
}
catch (Exception ex)
{
Logger.Error($"Unexpected error on attempt {attempt}", ex);
if (attempt < Config.MAX_RETRIES)
{
await Task.Delay(Config.RETRY_DELAY);
}
}
}
Logger.Error($"Failed to fetch questions after {Config.MAX_RETRIES} attempts");
return null;
}
}
// ============================================================================
// Trivia Game (Accuracy & Agility)
// ============================================================================
public class AnswerRecord
{
public string Question { get; set; }
public string Selected { get; set; }
public string Correct { get; set; }
public bool IsCorrect { get; set; }
public AnswerRecord(string question, string selected, string correct, bool isCorrect)
{
Question = question;
Selected = selected;
Correct = correct;
IsCorrect = isCorrect;
}
}
public class TriviaGame
{
private readonly List<Question> _questions;
private int _currentQuestionIndex = 0;
private int _score = 0;
private readonly List<AnswerRecord> _answersGiven = new List<AnswerRecord>();
public TriviaGame(List<Question> questions)
{
_questions = questions;
}
public Question? GetCurrentQuestion()
{
if (_currentQuestionIndex < _questions.Count)
{
return _questions[_currentQuestionIndex];
}
return null;
}
public bool SubmitAnswer(string selectedAnswer)
{
var question = GetCurrentQuestion();
if (question == null)
{
return false;
}
bool isCorrect = selectedAnswer == question.CorrectAnswer;
_answersGiven.Add(new AnswerRecord(
question.QuestionText,
selectedAnswer,
question.CorrectAnswer,
isCorrect
));
if (isCorrect)
{
_score++;
Logger.Debug($"Correct answer. Score: {_score}/{_answersGiven.Count}");
}
else
{
Logger.Debug($"Incorrect answer. Correct was: {question.CorrectAnswer}");
}
_currentQuestionIndex++;
return isCorrect;
}
public bool IsGameOver() => _currentQuestionIndex >= _questions.Count;
public int GetScore() => _score;
public int GetQuestionCount() => _questions.Count;
public double GetScorePercentage()
{
if (_answersGiven.Count == 0)
return 0;
return (_score / (double)_answersGiven.Count) * 100;
}
public List<AnswerRecord> GetAnswersGiven() => _answersGiven;
}
// ============================================================================
// Console UI
// ============================================================================
public class ConsoleUI
{
public void PrintHeader(string text)
{
Console.WriteLine("\n" + new string('=', 80));
Console.WriteLine($" {text}");
Console.WriteLine(new string('=', 80));
}
public void PrintQuestion(Question question, int questionNumber, int total)
{
Console.WriteLine($"\n[Question {questionNumber}/{total}]");
Console.WriteLine($"Category: {question.Category}");
Console.WriteLine($"Difficulty: {question.Difficulty.ToUpper()}");
Console.WriteLine($"\n{question.QuestionText}\n");
}
public void PrintOptions(List<string> options)
{
for (int i = 0; i < options.Count; i++)
{
Console.WriteLine($" {i + 1}. {options[i]}");
}
}
public int GetUserSelection(int numOptions)
{
while (true)
{
Console.Write($"\nYour answer (1-{numOptions}): ");
if (int.TryParse(Console.ReadLine(), out int selection))
{
if (selection >= 1 && selection <= numOptions)
{
return selection;
}
else
{
Console.WriteLine($"Please enter a number between 1 and {numOptions}");
}
}
else
{
Console.WriteLine("Invalid input. Please enter a number.");
}
}
}
public void PrintAnswerFeedback(bool isCorrect, string correctAnswer)
{
if (isCorrect)
{
Console.WriteLine("\n✓ CORRECT!");
}
else
{
Console.WriteLine($"\n✗ INCORRECT. The correct answer was: {correctAnswer}");
}
}
public void PrintFinalScore(TriviaGame game)
{
PrintHeader("GAME OVER - FINAL RESULTS");
Console.WriteLine($"\nTotal Score: {game.GetScore()}/{game.GetQuestionCount()}");
Console.WriteLine($"Percentage: {game.GetScorePercentage():F1}%");
Console.WriteLine("\n" + new string('-', 80));
Console.WriteLine("Question Summary:\n");
var answers = game.GetAnswersGiven();
for (int i = 0; i < answers.Count; i++)
{
var answer = answers[i];
string status = answer.IsCorrect ? "✓" : "✗";
Console.WriteLine($"{i + 1}. {status} {answer.Question}");
Console.WriteLine($" Your answer: {answer.Selected}");
if (!answer.IsCorrect)
{
Console.WriteLine($" Correct answer: {answer.Correct}");
}
Console.WriteLine();
}
}
public void PromptContinue()
{
Console.Write("\nPress Enter to continue to the next question...");
Console.ReadLine();
}
}
// ============================================================================
// Main Application
// ============================================================================
class Program
{
static async Task Main(string[] args)
{
Logger.Info("Starting Trivia Q&A Application");
var ui = new ConsoleUI();
try
{
ui.PrintHeader("TRIVIA Q&A - OPEN TRIVIA DATABASE");
Console.WriteLine(
"\nFetching trivia questions from the Open Trivia Database...");
// Fetch questions from API
var client = new TriviaAPIClient();
var triviaResponse = await client.FetchQuestionsAsync();
if (triviaResponse == null || triviaResponse.Results.Count == 0)
{
Console.WriteLine(
"\n✗ Failed to fetch trivia questions. Please check your connection and try again.");
Logger.Error("Application terminated due to API fetch failure");
return;
}
// Initialize game
var game = new TriviaGame(triviaResponse.Results);
// Run game loop
while (!game.IsGameOver())
{
var question = game.GetCurrentQuestion();
if (question == null)
{
break;
}
int questionNumber = game.GetAnswersGiven().Count + 1;
int totalQuestions = game.GetQuestionCount();
ui.PrintQuestion(question, questionNumber, totalQuestions);
var options = question.GetAllAnswers();
ui.PrintOptions(options);
// Get user's answer
int selectionIndex = ui.GetUserSelection(options.Count) - 1;
string selectedAnswer = options[selectionIndex];
// Check answer and provide feedback
bool isCorrect = game.SubmitAnswer(selectedAnswer);
ui.PrintAnswerFeedback(isCorrect, question.CorrectAnswer);
// Pause before next question
if (!game.IsGameOver())
{
ui.PromptContinue();
}
}
// Display final results
ui.PrintFinalScore(game);
Logger.Info(
$"Game completed. Final score: {game.GetScore()}/{game.GetQuestionCount()}");
}
catch (OperationCanceledException)
{
Console.WriteLine("\n\n✗ Game interrupted by user.");
Logger.Info("Game interrupted by user");
}
catch (Exception ex)
{
Logger.Error("Unexpected error during game", ex);
Console.WriteLine($"\n✗ An unexpected error occurred: {ex.Message}");
}
}
}