Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
323 lines (276 loc) · 10.1 KB
/
Copy pathapp.js
File metadata and controls
323 lines (276 loc) · 10.1 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
/* Dieser Code wurde teilweise mit Hilfe von KI erzeugt, und sorgfältig geprüft. */
const quizLength = 5;
const state = {
monuments: [],
questions: [],
currentIndex: 0,
score: 0,
answered: false,
};
const screens = {
loading: document.querySelector("#loading-screen"),
quiz: document.querySelector("#quiz-screen"),
result: document.querySelector("#result-screen"),
error: document.querySelector("#error-screen"),
};
const elements = {
score: document.querySelector("#score"),
progress: document.querySelector("#progress-bar"),
round: document.querySelector("#round-label"),
category: document.querySelector("#category-label"),
photo: document.querySelector("#photo"),
credit: document.querySelector("#photo-credit"),
creditLink: document.querySelector("#photo-credit-link"),
answers: document.querySelector("#answers"),
feedback: document.querySelector("#feedback"),
next: document.querySelector("#next-button"),
resultSummary: document.querySelector("#result-summary"),
finalScore: document.querySelector("#final-score"),
retry: document.querySelector("#retry-button"),
restart: document.querySelector("#restart-button"),
};
const normalize = (value) => value
.toLowerCase()
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^a-z0-9]+/g, " ")
.trim();
const levenshtein = (left, right) => {
if (left === right) return 0;
if (left.length === 0) return right.length;
if (right.length === 0) return left.length;
const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
for (let i = 0; i < left.length; i += 1) {
const current = [i + 1];
for (let j = 0; j < right.length; j += 1) {
const cost = left[i] === right[j] ? 0 : 1;
current.push(Math.min(
current[j] + 1,
previous[j + 1] + 1,
previous[j] + cost,
));
}
previous.splice(0, previous.length, ...current);
}
return previous[previous.length - 1];
};
const calculateSimilarity = (candidate, correct) => {
const candidateText = normalize(candidate);
const correctText = normalize(correct);
const maxLength = Math.max(candidateText.length, correctText.length, 1);
const distance = levenshtein(candidateText, correctText);
return 1 - (distance / maxLength);
};
const shuffle = (items) => [...items].sort(() => Math.random() - 0.5);
const getQuestionOptions = (correctMonument, allMonuments) => {
const candidates = allMonuments
.filter((monument) => monument.name !== correctMonument.name)
.map((monument) => ({
...monument,
similarity: calculateSimilarity(monument.name, correctMonument.name),
sameCategory: monument.category === correctMonument.category,
}))
.filter((monument) => monument.similarity > 0.15 || monument.sameCategory)
.sort((left, right) => {
const categoryDifference = Number(right.sameCategory) - Number(left.sameCategory);
if (categoryDifference !== 0) return categoryDifference;
return right.similarity - left.similarity;
})
.slice(0, 12);
if (candidates.length < 3) {
throw new Error("Nicht genug ähnliche Denkmäler für die Antwortmöglichkeiten vorhanden.");
}
const options = shuffle([
correctMonument,
...candidates.slice(0, 3),
]);
return shuffle(options.map((monument) => monument.name));
};
const showScreen = (name) => {
Object.entries(screens).forEach(([key, screen]) => {
screen.classList.toggle("visible", key === name);
});
};
const showImage = (url) => {
const largeUrl = getLargeImageUrl(url);
elements.photo.onerror = () => {
// Größere Version nicht verfügbar (z. B. Original kleiner): auf die Original-URL zurückfallen
elements.photo.onerror = null;
if (elements.photo.src !== url) elements.photo.src = url;
};
elements.photo.src = largeUrl;
elements.photo.alt = "Foto des zu ratenden Denkmals";
elements.photo.classList.remove("is-hidden");
};
const isHttpUrl = (value) => /^https?:\/\//i.test(value || "");
const thumbWidth = 1280;
// Wikimedia-Thumbnails (z. B. .../thumb/e/e3/Datei.jpg/250px-Datei.jpg?utm_source=...)
// auf eine größere Breite umschreiben; alle anderen URLs bleiben unverändert.
const getLargeImageUrl = (url) => {
if (!url) return url;
try {
const parsed = new URL(url);
const isThumbHost = parsed.hostname === "thumb.wikimedia.org"
|| (parsed.hostname === "upload.wikimedia.org" && parsed.pathname.includes("/thumb/"));
if (!isThumbHost) return url;
const match = parsed.pathname.match(/^(.*\/)(\d+)px-([^/]+)$/);
if (!match) return url;
parsed.hostname = "upload.wikimedia.org";
parsed.pathname = `${match[1]}${thumbWidth}px-${match[3]}`;
parsed.search = "";
return parsed.toString();
} catch {
return url;
}
};
const showCredit = (text, url) => {
if (!text) {
elements.credit.hidden = true;
return;
}
elements.creditLink.textContent = text;
if (isHttpUrl(url)) {
elements.creditLink.href = url;
elements.creditLink.title = "Bildquelle in neuem Fenster öffnen";
elements.creditLink.removeAttribute("aria-disabled");
} else {
elements.creditLink.removeAttribute("href");
elements.creditLink.removeAttribute("title");
elements.creditLink.setAttribute("aria-disabled", "true");
}
elements.credit.hidden = false;
};
const openCreditWindow = (event) => {
const url = elements.creditLink.getAttribute("href");
if (!isHttpUrl(url)) {
event.preventDefault();
return;
}
// Separates Fenster (Popup); wird es blockiert, greift der normale Link (neuer Tab)
const popup = window.open(url, "_blank", "noopener,noreferrer,width=1100,height=800");
if (popup) event.preventDefault();
};
const buildQuestion = (monument, allMonuments) => {
const options = getQuestionOptions(monument, allMonuments);
return {
...monument,
options,
};
};
const createQuestions = (allMonuments) => {
const shuffled = shuffle(allMonuments);
return shuffled.slice(0, quizLength).map((monument) => buildQuestion(monument, allMonuments));
};
const updateScore = () => {
elements.score.textContent = state.score;
};
const renderQuestion = () => {
const question = state.questions[state.currentIndex];
if (!question) return;
state.answered = false;
elements.progress.style.width = `${((state.currentIndex + 1) / quizLength) * 100}%`;
elements.round.textContent = `Runde ${state.currentIndex + 1}`;
elements.category.textContent = question.category || "Unbekannte Kategorie";
showImage(question.photoUrl);
showCredit(question.photoSource, question.photoSourceUrl);
window.scrollTo({ top: 0, behavior: "auto" });
elements.feedback.hidden = true;
elements.feedback.className = "feedback";
elements.next.hidden = true;
elements.answers.replaceChildren();
question.options.forEach((option, index) => {
const button = document.createElement("button");
button.type = "button";
button.className = "answer-button";
button.textContent = option;
button.setAttribute("role", "listitem");
button.setAttribute("aria-label", `Antwort ${index + 1}: ${option}`);
button.dataset.answer = option;
button.addEventListener("click", () => handleAnswer(button, option, question));
elements.answers.append(button);
});
};
const handleAnswer = (button, selectedAnswer, question) => {
if (state.answered) return;
state.answered = true;
const correct = selectedAnswer === question.name;
const buttons = [...elements.answers.querySelectorAll(".answer-button")];
buttons.forEach((answerButton) => {
const isCorrect = answerButton.dataset.answer === question.name;
answerButton.disabled = true;
answerButton.classList.toggle("correct", isCorrect);
answerButton.classList.toggle("wrong", answerButton === button && !correct);
});
elements.feedback.hidden = false;
elements.feedback.classList.add(correct ? "success" : "error");
elements.feedback.textContent = correct
? `Richtig! ${question.name} ist die korrekte Antwort.`
: `Leider falsch. Die richtige Antwort lautet: ${question.name}.`;
if (correct) state.score += 1;
updateScore();
elements.next.hidden = false;
requestAnimationFrame(() => {
elements.next.scrollIntoView({ behavior: "smooth", block: "nearest" });
});
};
const advanceQuiz = () => {
state.currentIndex += 1;
if (state.currentIndex < quizLength) {
renderQuestion();
} else {
showResult();
}
};
const showResult = () => {
elements.resultSummary.textContent = state.score === quizLength
? "Perfekt! Du hast alle fünf Denkmäler erkannt."
: state.score >= 3
? "Gute Arbeit! Du hast die meisten Denkmäler richtig erkannt."
: "Nicht ganz. Ein weiterer Versuch lohnt sich!";
elements.finalScore.textContent = state.score;
showScreen("result");
};
const startQuiz = () => {
state.currentIndex = 0;
state.score = 0;
updateScore();
elements.progress.style.width = "20%";
state.questions = createQuestions(state.monuments);
renderQuestion();
showScreen("quiz");
};
const loadData = async () => {
try {
const response = await fetch("data/denkmaeler.geojson");
if (!response.ok) throw new Error("GeoJSON konnte nicht geladen werden.");
const data = await response.json();
state.monuments = (data.features || [])
.map((feature) => {
const properties = feature.properties || {};
return {
name: properties.kurzbezeic || "Unbekanntes Denkmal",
category: properties.kategorie || "Allgemein",
photoUrl: properties.fotourl || "",
photoSource: properties.fotosource || "",
photoSourceUrl: properties.fotosour_1 || "",
};
})
.filter((monument) => monument.name && monument.name !== "Unbekanntes Denkmal");
if (state.monuments.length < quizLength) {
throw new Error("Zu wenige Denkmäler für ein vollständiges Quiz vorhanden.");
}
startQuiz();
} catch (error) {
console.error(error);
showScreen("error");
}
};
elements.creditLink.addEventListener("click", openCreditWindow);
elements.next.addEventListener("click", advanceQuiz);
elements.restart.addEventListener("click", startQuiz);
elements.retry.addEventListener("click", () => {
showScreen("loading");
loadData();
});
showScreen("loading");
loadData();