forked from fbrcode/trivia-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTriviaAppDemo.java
More file actions
400 lines (333 loc) · 13.7 KB
/
TriviaAppDemo.java
File metadata and controls
400 lines (333 loc) · 13.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
package com.trivia.app;
import java.util.*;
import java.util.logging.*;
import java.text.SimpleDateFormat;
/**
* Trivia Q&A Application - Demo Version (Java)
*
* Uses mock data to demonstrate the application flow without requiring network access.
* Run with: mvn exec:java -Dexec.mainClass="com.trivia.app.TriviaAppDemo"
*/
// ============================================================================
// 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;
public Logger(String name, LogLevel level) {
this.name = name;
this.level = level;
}
private String formatMessage(LogLevel logLevel, String message) {
return String.format("%s - %s - %s - %s",
new 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.getMessage() : 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 Question {
private final String category;
private final String difficulty;
private final String questionText;
private final String correctAnswer;
private final List<String> incorrectAnswers;
public Question(String category, String difficulty, String question, String correctAnswer, List<String> incorrectAnswers) {
this.category = decodeHtmlEntities(category);
this.difficulty = difficulty;
this.questionText = decodeHtmlEntities(question);
this.correctAnswer = decodeHtmlEntities(correctAnswer);
this.incorrectAnswers = incorrectAnswers.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;
}
}
// ============================================================================
// Mock Data Provider
// ============================================================================
class MockTriviaProvider {
public static List<Question> getMockData() {
return Arrays.asList(
new Question(
"Entertainment: Comics",
"hard",
"Better known by his nickname Logan, what is Wolverine's birth name?",
"James Howlett",
Arrays.asList("Logan Wolf", "Thomas Wilde", "John Savage")
),
new Question(
"History",
"easy",
"Which one of these countries was NOT in the Central Powers during WWI?",
"Spain",
Arrays.asList("Austria-Hungary", "Turkey", "Germany")
),
new Question(
"Entertainment: Video Games",
"easy",
"When was "Luigi's Mansion 3" released?",
"October 31st, 2019",
Arrays.asList("January 13th, 2019", "September 6th, 2018", "October 1st, 2019")
),
new Question(
"General Knowledge",
"easy",
"Earth is located in which galaxy?",
"The Milky Way Galaxy",
Arrays.asList("The Mars Galaxy", "The Galaxy Note", "The Black Hole")
),
new Question(
"Science: Gadgets",
"medium",
"In what year was the Oculus Rift revealed to the public through a Kickstarter campaign?",
"2012",
Arrays.asList("2010", "2011", "2013")
)
);
}
}
// ============================================================================
// Trivia Game
// ============================================================================
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 (Demo)
// ============================================================================
public class TriviaAppDemo {
public static void main(String[] args) {
logger.info("Starting Trivia Q&A Application (DEMO MODE)");
ConsoleUI ui = new ConsoleUI();
try {
ui.printHeader("TRIVIA Q&A - OPEN TRIVIA DATABASE (DEMO)");
System.out.println("\nLoading trivia questions (using mock data for demo)...\n");
List<Question> questions = MockTriviaProvider.getMockData();
if (questions == null || questions.isEmpty()) {
System.out.println("\n✗ Failed to load trivia questions.");
logger.error("Application terminated due to data load failure");
ui.close();
return;
}
System.out.println("✓ Loaded " + questions.size() + " questions\n");
TriviaGame game = new TriviaGame(questions);
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();
}
}
}