-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanswerScreen.js
More file actions
602 lines (510 loc) · 18.2 KB
/
answerScreen.js
File metadata and controls
602 lines (510 loc) · 18.2 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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
// answerScreen.js
/*
Answer screen that shows:
- Game results and scoring
- Interactive map with guess visualization
- Score statistics
- Play again options
*/
let currentAnswer = {
correctDistance: 0,
correctDirection: 0,
guessDistance: 0,
guessDirection: 0,
score: 0
};
let staticMapImg;
let mapInitialized = false;
function drawAnswerScreen() {
const useInteractiveMap = localStorage.getItem('useInteractiveMap') === 'true';
let mapX = 0;
let mapY = height / 2;
let mapW = width;
let mapH = height / 2;
if (height > width) {
mapW = width;
mapH = height / 2.75;
} else {
mapW = height / 2;
mapH = height / 2;
}
mapX = width/2 - mapW/2;
mapW = round(mapW);
mapH = round(mapH);
if (useInteractiveMap && !mapInitialized) {
// Ensure dimensions are integers
mapX = Math.floor(mapX);
mapY = Math.floor(mapY);
mapW = Math.floor(mapW);
mapH = Math.floor(mapH);
const initResult = interactiveMap.initialize(mapX, mapY, mapW, mapH);
if (initResult) {
interactiveMap.drawAnswer(currentAnswer);
mapInitialized = true;
}
} else if (!useInteractiveMap) {
if (!staticMapImg) {
loadStaticMap();
}
if (staticMapImg) {
imageMode(CORNER);
let { w: finalW, h: finalH } = drawMapWithAspectRatio(staticMapImg, mapW, mapH, mapX, mapY);
}
}
if (userSettings.practiceMode) {
// Use game screen's input handling but don't show joysticks
if (!distanceLocked) {
const beta = orientationService.getBeta();
if (beta !== null) {
// Map each order of magnitude to 10° segments
const ranges = [
{ max: 0.01, tiltRange: [0, 10] },
{ max: 0.1, tiltRange: [10, 20] },
{ max: 1, tiltRange: [20, 30] },
{ max: 10, tiltRange: [30, 40] },
{ max: 100, tiltRange: [40, 50] },
{ max: 1000, tiltRange: [50, 60] },
{ max: userSettings.radius, tiltRange: [60, 70] }
];
// Find which range we're in
for (let range of ranges) {
if (beta <= range.tiltRange[1]) {
// Calculate normalized position within this range
const rangeBeta = (beta - range.tiltRange[0]) /
(range.tiltRange[1] - range.tiltRange[0]);
// Map to the value range
const prevMax = ranges[ranges.indexOf(range) - 1]?.max || 0.001;
const value = prevMax + (range.max - prevMax) * rangeBeta;
// Apply rounding based on the range
if (value <= 0.01) {
userGuessDistance = Number(value.toFixed(3));
} else if (value <= 0.1) {
userGuessDistance = Number(value.toFixed(2));
} else if (value <= 10) {
userGuessDistance = Number(value.toFixed(1));
} else if (value <= 1000) {
userGuessDistance = Math.round(value);
} else if (value <= 10000) {
userGuessDistance = Math.round(value/10) * 10;
} else {
userGuessDistance = Math.round(value/100) * 100;
}
break;
}
}
userGuessDistance = constrain(userGuessDistance, 0.001, userSettings.radius);
}
}
if (!directionLocked) {
userGuessDirection = orientationService.getHeading();
}
// Update current answer with new values
if (userGuessDistance !== currentAnswer.guessDistance ||
userGuessDirection !== currentAnswer.guessDirection) {
// Constrain distance to max range setting
userGuessDistance = constrain(userGuessDistance, 0.001, userSettings.radius);
let score = scoringService.calculateScore(
currentAnswer.correctDistance,
userGuessDistance,
currentAnswer.correctDirection,
userGuessDirection,
currentAnswer.playerLat,
currentAnswer.playerLon,
currentAnswer.targetLat,
currentAnswer.targetLon
);
// Update display values but don't save to history
currentAnswer.guessDistance = userGuessDistance;
currentAnswer.guessDirection = userGuessDirection;
currentAnswer.score1 = score.score1;
currentAnswer.score2 = score.score2;
// Update only paths on the map, not markers
if (interactiveMap.map) {
interactiveMap.updatePaths(currentAnswer);
}
}
}
let distanceError = Math.abs(currentAnswer.correctDistance - currentAnswer.guessDistance);
let distanceAccuracy = Math.max(0, 100 - (distanceError / currentAnswer.correctDistance * 100));
let dirError = Math.min(
Math.abs(currentAnswer.correctDirection - currentAnswer.guessDirection),
360 - Math.abs(currentAnswer.correctDirection - currentAnswer.guessDirection)
);
let directionAccuracy = Math.max(0, 100 - (dirError / 180 * 100));
textSize(32);
textAlign(CENTER, CENTER);
noStroke();
textStyle(BOLD);
fill(getTextColor());
// Create clickable location name
let locationY = height/4 - height/8;
let locationX = width/2;
let maxWidth = width * 0.8;
let textH = 40;
// Create or update the link element
let linkId = 'location-link';
let locationLink = document.getElementById(linkId);
if (!locationLink) {
locationLink = document.createElement('a');
locationLink.id = linkId;
locationLink.style.position = 'absolute';
locationLink.style.textAlign = 'center';
locationLink.style.textDecoration = 'none';
locationLink.style.color = 'inherit';
locationLink.style.cursor = 'pointer';
locationLink.style.fontFamily = 'Helvetica, Arial, sans-serif';
locationLink.style.zIndex = '0';
locationLink.style.whiteSpace = 'nowrap';
locationLink.rel = 'noopener noreferrer';
locationLink.target = '_blank';
document.body.appendChild(locationLink);
}
// Hide link when dropdown is open
locationLink.style.display = dropdownMenu.isOpen ? 'none' : 'flex';
if (!dropdownMenu.isOpen) {
// Only update link if dropdown is closed
const offset = getCanvasOffset();
locationLink.style.left = (offset.x + locationX - maxWidth/2) + 'px';
locationLink.style.top = (offset.y + locationY - textH/2) + 'px';
locationLink.style.width = maxWidth + 'px';
locationLink.style.height = textH + 'px';
locationLink.style.alignItems = 'center';
locationLink.style.justifyContent = 'center';
// Set the link URL
const origin = `${currentAnswer.playerLat},${currentAnswer.playerLon}`;
const destination = `${currentAnswer.targetLat},${currentAnswer.targetLon}`;
locationLink.href = `https://www.google.com/maps/dir/?api=1&destination=${destination}&travelmode=best`;
// Update link text and base style
locationLink.style.color = getComputedStyle(document.documentElement).getPropertyValue('--text-color');
locationLink.style.fontWeight = 'bold';
locationLink.style.lineHeight = textH + 'px';
// Set text and adjust font size if needed
locationLink.innerText = currentQuestion.name;
// Start with default size and reduce if too wide
let fontSize = 32;
locationLink.style.fontSize = fontSize + 'px';
// Measure text width using a temporary canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.font = `bold ${fontSize}px Helvetica, Arial, sans-serif`;
let textWidth = ctx.measureText(currentQuestion.name).width;
// Reduce font size until text fits
while (textWidth > maxWidth * 0.95 && fontSize > 16) {
fontSize -= 1;
ctx.font = `bold ${fontSize}px Helvetica, Arial, sans-serif`;
textWidth = ctx.measureText(currentQuestion.name).width;
}
locationLink.style.fontSize = fontSize + 'px';
}
// Check if mouse is over location name for visual feedback
if (mouseX > locationX - maxWidth/2 &&
mouseX < locationX + maxWidth/2 &&
mouseY > locationY - textH/2 &&
mouseY < locationY + textH/2) {
cursor(HAND);
stroke(getTextColor());
strokeWeight(1);
line(locationX - textWidth(currentQuestion.name)/2, locationY + textH/3,
locationX + textWidth(currentQuestion.name)/2, locationY + textH/3);
} else {
cursor(AUTO);
}
// Add country name
textSize(18);
noStroke();
textStyle(NORMAL);
fill(getTextColor());
text(currentQuestion.country, width/2, locationY + 35);
let centerY = height/4+height/20;
let radius = min(width, height) * 0.15;
let spacing = radius * 3;
drawAccuracyCircle(
width/2 - spacing/2,
centerY,
radius,
distanceAccuracy,
"Distance",
currentAnswer.guessDistance + " km",
currentAnswer.correctDistance + " km"
);
drawAccuracyCircle(
width/2 + spacing/2,
centerY,
radius,
directionAccuracy,
"Direction",
Math.round(currentAnswer.guessDirection) + "°",
Math.round(currentAnswer.correctDirection) + "°"
);
let guessedCoords = computeDestinationLatLon(
currentAnswer.playerLat,
currentAnswer.playerLon,
currentAnswer.guessDistance,
currentAnswer.guessDirection
);
let differenceDistance = round(
calculateDistance(
guessedCoords.lat,
guessedCoords.lon,
currentAnswer.targetLat,
currentAnswer.targetLon
)
);
textSize(20);
fill(getTextColor());
text("Off by " + differenceDistance + " km", width/2, height/4 + height/5.5);
fill(getScoreP5Color(currentAnswer.score2));
text("Score: " + currentAnswer.score2 + "%", width/2, height/4 + height/4.5);
// Update score display
//textSize(18);
//fill(getScoreP5Color(currentAnswer.score2));
//text("New Score: " + currentAnswer.score2 + "%", width/2 - 100, height/4 + height/4.5);
//fill(getScoreP5Color(currentAnswer.score1));
//text("Old Score: " + currentAnswer.score1 + "%", width/2 + 100, height/4 + height/4.5);
// After drawing the score
const currentDataset = localStorage.getItem('selectedDataset') || 'global';
const avgScore = scoringService.getAverageScore(currentDataset);
const bestScore = scoringService.getBestScore(currentDataset);
// Save score when entering answer screen
if (!this.scoreSaved) {
scoringService.saveScore(currentAnswer);
this.scoreSaved = true;
}
let btnW = 150, btnH = 50;
let playAgainX = width/2 - btnW/2;
let playAgainY = height * 0.9;
drawInteractiveButton(
playAgainX, playAgainY,
btnW, btnH,
enteredFromSearch ? "New Search" : "Play Again",
() => {
if (enteredFromSearch) {
enteredFromSearch = false;
goToScreen("search");
} else {
resetLockStates();
pickNewQuestion();
goToScreen("game");
}
}
);
// Draw dropdown menu
dropdownMenu.draw('answer');
if (drawCloseButton()) {
return;
}
}
function drawAccuracyCircle(x, y, radius, accuracy, label, guessValue, correctValue) {
// Parse values to numbers for comparison
const guessNum = parseFloat(guessValue);
const correctNum = parseFloat(correctValue);
// Special handling for direction angles
const isDirection = label === "Direction";
let isOvershot = false;
if (isDirection) {
// Calculate the shortest path between angles
let diff = ((guessNum - correctNum + 180 + 360) % 360) - 180;
isOvershot = diff > 0; // Positive diff means we need to go counterclockwise
} else {
isOvershot = guessNum > correctNum;
}
noFill();
stroke(getButtonColor());
strokeWeight(10);
circle(x, y, radius * 2);
let col = getScoreP5Color(accuracy);
stroke(col);
push();
if (isOvershot) {
// For overshot values, flip the arc horizontally
translate(x, y);
scale(-1, 1);
translate(-x, -y);
}
// Draw accuracy arc
arc(x, y, radius * 2, radius * 2, -90, -90 + (accuracy * 3.6));
pop();
noStroke();
fill(getTextColor());
textAlign(CENTER, CENTER);
textSize(16);
text(label, x, y - radius/2);
textSize(24);
fill(col);
// Add arrow to indicate clockwise/counterclockwise for direction
//text(guessValue + (isDirection ? (isOvershot ? "↺" : "↻") : (isOvershot ? "↑" : "↓")), x, y);
text(guessValue, x, y);
textSize(16);
fill(getTextColor());
text("(" + correctValue + ")", x, y + radius/2);
// Add accuracy percentage for debugging
//textAlign(LEFT, CENTER);
//textSize(14);
//text(Math.round(accuracy) + "%", x + radius + 10, y);
}
function loadStaticMap() {
let screenW = width;
let screenH = height;
let isPortrait = (screenH > screenW);
let mapW, mapH;
if (isPortrait) {
mapW = min(screenW, 640);
mapH = min(screenH / 3, 640);
} else {
mapW = 640;
mapH = 640;
}
mapW = round(mapW);
mapH = round(mapH);
let scale = 2;
let pLat = currentAnswer.playerLat;
let pLon = currentAnswer.playerLon;
let tLat = currentAnswer.targetLat;
let tLon = currentAnswer.targetLon;
let guessCoords = computeDestinationLatLon(
pLat, pLon,
currentAnswer.guessDistance,
currentAnswer.guessDirection
);
let gLat = guessCoords.lat;
let gLon = guessCoords.lon;
let targetPoints = generateGreatCirclePoints(pLat, pLon, tLat, tLon, 64);
let targetPathString = buildPathString(targetPoints, "0x000000", 3);
let differencePoints = generateGreatCirclePoints(gLat, gLon, tLat, tLon, 64);
let differencePathString = buildPathString(differencePoints, "0x00000033", 1);
let guessColorHex = getScoreHexForMap(currentAnswer.score);
let guessPoints = generateGreatCirclePoints(pLat, pLon, gLat, gLon, 64);
let guessPathString = buildPathString(guessPoints, guessColorHex, 3);
let params = [
`size=${mapW}x${mapH}`,
`scale=${scale}`,
`style=feature:all|element:labels|visibility:off`,
`style=feature:road|element:geometry|visibility:off`,
`style=feature:poi|visibility:off`,
`style=feature:transit|visibility:off`,
`markers=color:black|label:X|${tLat},${tLon}`,
targetPathString,
guessPathString,
differencePathString,
`key=${GOOGLE_MAPS_JS_API_KEY}`
];
let base = "https://maps.googleapis.com/maps/api/staticmap";
let url = base + "?" + params.join("&");
staticMapImg = loadImage(
url,
() => {},
err => console.error("Map load error:", err)
);
}
function buildPathString(pointsArray, colorHex, weight) {
let path = `path=color:${colorHex}|weight:${weight}`;
for (let p of pointsArray) {
path += `|${p.lat},${p.lon}`;
}
return path;
}
function drawMapWithAspectRatio(img, maxW, maxH, x, y) {
let aspect = img.width / img.height;
let finalW = maxW;
let finalH = finalW / aspect;
image(img, x, y, finalW, finalH);
return { w: finalW, h: finalH };
}
function getScoreP5Color(score) {
score = constrain(score, 0, 100);
let isDark = document.documentElement.getAttribute('data-theme') === 'dark';
let cRed = isDark ? color(200, 0, 0) : color(255, 0, 0);
let cGreen = isDark ? color(0, 200, 0) : color(0, 255, 0);
return lerpColor(cRed, cGreen, score / 100);
}
function p5ColorToHexString(c) {
let r = Math.round(red(c));
let g = Math.round(green(c));
let b = Math.round(blue(c));
let rr = r.toString(16).padStart(2, '0');
let gg = g.toString(16).padStart(2, '0');
let bb = b.toString(16).padStart(2, '0');
return rr + gg + bb;
}
function getScoreHexForMap(score) {
let p5col = getScoreP5Color(score);
let hexString = p5ColorToHexString(p5col);
return "0x" + hexString;
}
function computeDestinationLatLon(lat1_deg, lon1_deg, distance_km, bearing_deg) {
const R = 6371;
let lat1 = radians(lat1_deg);
let lon1 = radians(lon1_deg);
let bearing = radians(bearing_deg);
let d = distance_km;
let lat2 = Math.asin(
Math.sin(lat1) * Math.cos(d / R) +
Math.cos(lat1) * Math.sin(d / R) * Math.cos(bearing)
);
let lon2 = lon1 + Math.atan2(
Math.sin(bearing) * Math.sin(d / R) * Math.cos(lat1),
Math.cos(d / R) - Math.sin(lat1) * Math.sin(lat2)
);
let lat2_deg = degrees(lat2);
let lon2_deg = degrees(lon2);
lon2_deg = ((lon2_deg + 540) % 360) - 180;
return { lat: lat2_deg, lon: lon2_deg };
}
function generateGreatCirclePoints(lat1, lon1, lat2, lon2, n) {
const φ1 = radians(lat1);
const λ1 = radians(lon1);
const φ2 = radians(lat2);
const λ2 = radians(lon2);
const d = centralAngle(φ1, λ1, φ2, λ2);
let points = [];
for (let i = 0; i <= n; i++) {
let f = i / n;
let A = Math.sin((1 - f) * d) / Math.sin(d);
let B = Math.sin(f * d) / Math.sin(d);
let x = A * Math.cos(φ1) * Math.cos(λ1) + B * Math.cos(φ2) * Math.cos(λ2);
let y = A * Math.cos(φ1) * Math.sin(λ1) + B * Math.cos(φ2) * Math.sin(λ2);
let z = A * Math.sin(φ1) + B * Math.sin(φ2);
let φi = Math.atan2(z, Math.sqrt(x * x + y * y));
let λi = Math.atan2(y, x);
let lat_i = degrees(φi);
let lon_i = degrees(λi);
lon_i = ((lon_i + 540) % 360) - 180;
points.push({ lat: lat_i, lon: lon_i });
}
return points;
}
function centralAngle(φ1, λ1, φ2, λ2) {
return Math.acos(
Math.sin(φ1) * Math.sin(φ2) +
Math.cos(φ1) * Math.cos(φ2) * Math.cos(λ2 - λ1)
);
}
function radians(deg) { return deg * Math.PI / 180; }
function degrees(rad) { return rad * 180 / Math.PI; }
// Add to cleanup when leaving answer screen
function cleanupAnswerScreen() {
staticMapImg = null;
interactiveMap.remove();
mapInitialized = false;
this.scoreSaved = false;
userSettings.practiceMode = false; // Turn off practice mode
// Remove location link
const locationLink = document.getElementById('location-link');
if (locationLink) {
locationLink.remove();
}
}
// Add a window resize handler
function windowResized() {
if (currentScreen === "answer") {
mapInitialized = false;
}
}
function truncateText(text, maxWidth) {
let ellipsis = '...';
let truncated = text;
while (textWidth(truncated + ellipsis) > maxWidth && truncated.length > 0) {
truncated = truncated.slice(0, -1);
}
return truncated + ellipsis;
}