forked from fbrcode/trivia-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTriviaApp.java
More file actions
509 lines (414 loc) · 17.5 KB
/
TriviaApp.java
File metadata and controls
509 lines (414 loc) · 17.5 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
package com.trivia.app;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.*;
import java.util.logging.*;
import com.google.gson.*;
/**
* Trivia Q&A Application (Java)
*
* 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
*/
// ============================================================================
// Configuration & Constants
// ============================================================================
class Config {
public static final String API_ENDPOINT = "https://opentdb.com/api.php?amount=10";
public static final int REQUEST_TIMEOUT = 10000; // milliseconds
public static final int MAX_RETRIES = 3;
public static final int RETRY_DELAY = 1000; // milliseconds
}
// ============================================================================
// Logging Configuration
// ============================================================================
enum LogLevel {
DEBUG(0),
INFO(1),
WARNING(2),
ERROR(3);
private final int level;
LogLevel(int level) {
this.level = level;
}
public int getLevel() {
return level;
}
}
class Logger {
private final String name;
private final LogLevel level;
private final java.util.logging.Logger javaLogger;
public Logger(String name, LogLevel level) {
this.name = name;
this.level = level;
this.javaLogger = java.util.logging.Logger.getLogger(name);
}
private String formatMessage(LogLevel logLevel, String message) {
return String.format("%s - %s - %s - %s",
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
name,
logLevel.name(),
message);
}
public void debug(String message) {
if (level.getLevel() <= LogLevel.DEBUG.getLevel()) {
System.out.println(formatMessage(LogLevel.DEBUG, message));
}
}
public void info(String message) {
if (level.getLevel() <= LogLevel.INFO.getLevel()) {
System.out.println(formatMessage(LogLevel.INFO, message));
}
}
public void warning(String message) {
if (level.getLevel() <= LogLevel.WARNING.getLevel()) {
System.out.println(formatMessage(LogLevel.WARNING, message));
}
}
public void error(String message, Exception exception) {
if (level.getLevel() <= LogLevel.ERROR.getLevel()) {
String errorMsg = exception != null ? message + "\n" + exception.getStackTrace() : message;
System.err.println(formatMessage(LogLevel.ERROR, errorMsg));
}
}
public void error(String message) {
error(message, null);
}
}
private static final Logger logger = new Logger("trivia_app", LogLevel.INFO);
// ============================================================================
// Domain Models
// ============================================================================
class TriviaQuestionDto {
@SerializedName("type")
private String type;
@SerializedName("difficulty")
private String difficulty;
@SerializedName("category")
private String category;
@SerializedName("question")
private String question;
@SerializedName("correct_answer")
private String correctAnswer;
@SerializedName("incorrect_answers")
private List<String> incorrectAnswers;
// Getters
public String getType() { return type; }
public String getDifficulty() { return difficulty; }
public String getCategory() { return category; }
public String getQuestion() { return question; }
public String getCorrectAnswer() { return correctAnswer; }
public List<String> getIncorrectAnswers() { return incorrectAnswers != null ? incorrectAnswers : new ArrayList<>(); }
}
class TriviaResponseDto {
@SerializedName("response_code")
private int responseCode;
@SerializedName("results")
private List<TriviaQuestionDto> results;
public int getResponseCode() { return responseCode; }
public List<TriviaQuestionDto> getResults() { return results != null ? results : new ArrayList<>(); }
}
class Question {
private final String category;
private final String difficulty;
private final String questionText;
private final String correctAnswer;
private final List<String> incorrectAnswers;
public Question(TriviaQuestionDto dto) {
this.category = decodeHtmlEntities(dto.getCategory() != null ? dto.getCategory() : "Unknown");
this.difficulty = dto.getDifficulty() != null ? dto.getDifficulty() : "unknown";
this.questionText = decodeHtmlEntities(dto.getQuestion() != null ? dto.getQuestion() : "");
this.correctAnswer = decodeHtmlEntities(dto.getCorrectAnswer() != null ? dto.getCorrectAnswer() : "");
this.incorrectAnswers = dto.getIncorrectAnswers().stream()
.map(this::decodeHtmlEntities)
.toList();
}
private String decodeHtmlEntities(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return text
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace(""", "\"")
.replace("'", "'")
.replace("'", "'");
}
public String getCategory() { return category; }
public String getDifficulty() { return difficulty; }
public String getQuestionText() { return questionText; }
public String getCorrectAnswer() { return correctAnswer; }
public List<String> getIncorrectAnswers() { return incorrectAnswers; }
public List<String> getAllAnswers() {
List<String> answers = new ArrayList<>(incorrectAnswers);
answers.add(correctAnswer);
Collections.shuffle(answers);
return answers;
}
}
class TriviaResponse {
private final int responseCode;
private final List<Question> results;
private TriviaResponse(int responseCode, List<Question> results) {
this.responseCode = responseCode;
this.results = results;
}
public static TriviaResponse fromJson(TriviaResponseDto dto) throws Exception {
if (dto.getResponseCode() != 0) {
throw new IllegalArgumentException("API returned error code: " + dto.getResponseCode());
}
List<Question> questions = dto.getResults().stream()
.map(Question::new)
.toList();
return new TriviaResponse(dto.getResponseCode(), new ArrayList<>(questions));
}
public int getResponseCode() { return responseCode; }
public List<Question> getResults() { return results; }
}
// ============================================================================
// API Client (Resilience & Reliability)
// ============================================================================
class TriviaAPIClient {
private final String endpoint;
private final Duration timeout;
private final HttpClient httpClient;
private final Gson gson;
public TriviaAPIClient(String endpoint, int timeoutMs) {
this.endpoint = endpoint;
this.timeout = Duration.ofMillis(timeoutMs);
this.httpClient = HttpClient.newBuilder()
.connectTimeout(timeout)
.build();
this.gson = new Gson();
}
public TriviaAPIClient() {
this(Config.API_ENDPOINT, Config.REQUEST_TIMEOUT);
}
public TriviaResponse fetchQuestions() throws Exception {
for (int attempt = 1; attempt <= Config.MAX_RETRIES; attempt++) {
try {
logger.info("Fetching questions from API (attempt " + attempt + "/" + Config.MAX_RETRIES + ")");
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(endpoint))
.timeout(timeout)
.GET()
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new IOException("HTTP " + response.statusCode());
}
logger.debug("API response status: " + response.statusCode());
TriviaResponseDto dto = gson.fromJson(response.body(), TriviaResponseDto.class);
TriviaResponse triviaResponse = TriviaResponse.fromJson(dto);
logger.info("Successfully fetched " + triviaResponse.getResults().size() + " questions");
return triviaResponse;
} catch (java.net.http.HttpTimeoutException e) {
logger.warning("Request timeout on attempt " + attempt);
if (attempt < Config.MAX_RETRIES) {
Thread.sleep(Config.RETRY_DELAY);
}
} catch (IOException e) {
logger.warning("Connection error on attempt " + attempt + ": " + e.getMessage());
if (attempt < Config.MAX_RETRIES) {
Thread.sleep(Config.RETRY_DELAY);
}
} catch (Exception e) {
logger.error("Error on attempt " + attempt, e);
if (attempt < Config.MAX_RETRIES) {
Thread.sleep(Config.RETRY_DELAY);
}
}
}
logger.error("Failed to fetch questions after " + Config.MAX_RETRIES + " attempts");
return null;
}
}
// ============================================================================
// Trivia Game (Accuracy & Agility)
// ============================================================================
class AnswerRecord {
private final String question;
private final String selected;
private final String correct;
private final boolean isCorrect;
public AnswerRecord(String question, String selected, String correct, boolean isCorrect) {
this.question = question;
this.selected = selected;
this.correct = correct;
this.isCorrect = isCorrect;
}
public String getQuestion() { return question; }
public String getSelected() { return selected; }
public String getCorrect() { return correct; }
public boolean isCorrect() { return isCorrect; }
}
class TriviaGame {
private final List<Question> questions;
private int currentQuestionIndex = 0;
private int score = 0;
private final List<AnswerRecord> answersGiven = new ArrayList<>();
public TriviaGame(List<Question> questions) {
this.questions = questions;
}
public Question getCurrentQuestion() {
if (currentQuestionIndex < questions.size()) {
return questions.get(currentQuestionIndex);
}
return null;
}
public boolean submitAnswer(String selectedAnswer) {
Question question = getCurrentQuestion();
if (question == null) {
return false;
}
boolean isCorrect = selectedAnswer.equals(question.getCorrectAnswer());
answersGiven.add(new AnswerRecord(
question.getQuestionText(),
selectedAnswer,
question.getCorrectAnswer(),
isCorrect
));
if (isCorrect) {
score++;
logger.debug("Correct answer. Score: " + score + "/" + answersGiven.size());
} else {
logger.debug("Incorrect answer. Correct was: " + question.getCorrectAnswer());
}
currentQuestionIndex++;
return isCorrect;
}
public boolean isGameOver() {
return currentQuestionIndex >= questions.size();
}
public int getScore() { return score; }
public int getQuestionCount() { return questions.size(); }
public double getScorePercentage() {
if (answersGiven.isEmpty()) return 0;
return (score / (double) answersGiven.size()) * 100;
}
public List<AnswerRecord> getAnswersGiven() { return answersGiven; }
}
// ============================================================================
// Console UI
// ============================================================================
class ConsoleUI {
private final Scanner scanner = new Scanner(System.in);
public void printHeader(String text) {
System.out.println("\n" + "=".repeat(80));
System.out.println(" " + text);
System.out.println("=".repeat(80));
}
public void printQuestion(Question question, int questionNumber, int total) {
System.out.println("\n[Question " + questionNumber + "/" + total + "]");
System.out.println("Category: " + question.getCategory());
System.out.println("Difficulty: " + question.getDifficulty().toUpperCase());
System.out.println("\n" + question.getQuestionText() + "\n");
}
public void printOptions(List<String> options) {
for (int i = 0; i < options.size(); i++) {
System.out.println(" " + (i + 1) + ". " + options.get(i));
}
}
public int getUserSelection(int numOptions) {
while (true) {
System.out.print("\nYour answer (1-" + numOptions + "): ");
try {
int selection = Integer.parseInt(scanner.nextLine().trim());
if (selection >= 1 && selection <= numOptions) {
return selection;
} else {
System.out.println("Please enter a number between 1 and " + numOptions);
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a number.");
}
}
}
public void printAnswerFeedback(boolean isCorrect, String correctAnswer) {
if (isCorrect) {
System.out.println("\n✓ CORRECT!");
} else {
System.out.println("\n✗ INCORRECT. The correct answer was: " + correctAnswer);
}
}
public void printFinalScore(TriviaGame game) {
printHeader("GAME OVER - FINAL RESULTS");
System.out.println("\nTotal Score: " + game.getScore() + "/" + game.getQuestionCount());
System.out.printf("Percentage: %.1f%%%n", game.getScorePercentage());
System.out.println("\n" + "-".repeat(80));
System.out.println("Question Summary:\n");
List<AnswerRecord> answers = game.getAnswersGiven();
for (int i = 0; i < answers.size(); i++) {
AnswerRecord answer = answers.get(i);
String status = answer.isCorrect() ? "✓" : "✗";
System.out.println((i + 1) + ". " + status + " " + answer.getQuestion());
System.out.println(" Your answer: " + answer.getSelected());
if (!answer.isCorrect()) {
System.out.println(" Correct answer: " + answer.getCorrect());
}
System.out.println();
}
}
public void promptContinue() {
System.out.print("\nPress Enter to continue to the next question...");
scanner.nextLine();
}
public void close() {
scanner.close();
}
}
// ============================================================================
// Main Application
// ============================================================================
public class TriviaApp {
public static void main(String[] args) {
logger.info("Starting Trivia Q&A Application");
ConsoleUI ui = new ConsoleUI();
try {
ui.printHeader("TRIVIA Q&A - OPEN TRIVIA DATABASE");
System.out.println("\nFetching trivia questions from the Open Trivia Database...");
TriviaAPIClient client = new TriviaAPIClient();
TriviaResponse triviaResponse = client.fetchQuestions();
if (triviaResponse == null || triviaResponse.getResults().isEmpty()) {
System.out.println("\n✗ Failed to fetch trivia questions. Please check your connection and try again.");
logger.error("Application terminated due to API fetch failure");
ui.close();
return;
}
TriviaGame game = new TriviaGame(triviaResponse.getResults());
while (!game.isGameOver()) {
Question question = game.getCurrentQuestion();
if (question == null) {
break;
}
int questionNumber = game.getAnswersGiven().size() + 1;
int totalQuestions = game.getQuestionCount();
ui.printQuestion(question, questionNumber, totalQuestions);
List<String> options = question.getAllAnswers();
ui.printOptions(options);
int selectionIndex = ui.getUserSelection(options.size()) - 1;
String selectedAnswer = options.get(selectionIndex);
boolean isCorrect = game.submitAnswer(selectedAnswer);
ui.printAnswerFeedback(isCorrect, question.getCorrectAnswer());
if (!game.isGameOver()) {
ui.promptContinue();
}
}
ui.printFinalScore(game);
logger.info("Game completed. Final score: " + game.getScore() + "/" + game.getQuestionCount());
} catch (Exception e) {
logger.error("Unexpected error during game", e);
System.out.println("\n✗ An unexpected error occurred: " + e.getMessage());
} finally {
ui.close();
}
}
}