-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1949 lines (1786 loc) · 68.4 KB
/
Copy pathmain.js
File metadata and controls
1949 lines (1786 loc) · 68.4 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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createSimulationClock } from "./simulation-clock.js";
import { dailySeed, readRecords, saveResult, bestForSeed, rankForResult } from "./progression.js";
import {
buildLoop,
choice,
clamp,
createRng,
dist,
generateStations as generateCityStations,
lerp,
hazardEffectsAtPoint,
projectPointToLoop,
randRange,
twoOptSpliceCycle,
} from "./game-core.js";
/* Loop Courier - dependency-free browser game
*
* Core: draw a closed loop, bot runs it, packages spawn at pickups and must be delivered
* to matching dropoffs before a deadline. Limited "splices" perform a 2-opt rewire on
* the loop edges (click two edges).
*/
(function () {
"use strict";
const TAU = Math.PI * 2;
let canvasScale = 1;
const SERVICE_RADIUS = 18; // Must match pickup/delivery radius for "on-route" logic.
const STATION_SNAP_RADIUS = 14; // While drawing, snap points to nearby stations for easier routes.
const TUTORIAL_DONE_KEY = "loopCourierTutorialDone.v1";
const COLORS = [
{ id: "red", label: "Red", fill: "#ef476f", stroke: "rgba(239, 71, 111, 0.95)" },
{ id: "blue", label: "Blue", fill: "#62c9ef", stroke: "rgba(98, 201, 239, 0.95)" },
{ id: "gold", label: "Gold", fill: "#ffd166", stroke: "rgba(255, 209, 102, 0.95)" },
];
function dot(ax, ay, bx, by) {
return ax * bx + ay * by;
}
function fmtTime(sec) {
const s = Math.max(0, Math.ceil(sec));
const m = Math.floor(s / 60);
const r = s % 60;
return `${m}:${String(r).padStart(2, "0")}`;
}
let manualClock = false;
let lastFrameAtMs = performance.now();
const simulationClock = createSimulationClock((dt) => {
simulate(dt);
return mode === "run" || mode === "splice";
});
function nowMs() {
return simulationClock.timeMs;
}
function round(value, places = 1) {
const factor = 10 ** places;
return Math.round(value * factor) / factor;
}
function uniqByKey(points, minDistPx) {
const out = [];
let last = null;
for (const p of points) {
if (!last || dist(p, last) >= minDistPx) {
out.push({ x: p.x, y: p.y });
last = p;
}
}
return out;
}
function simplifyByAngle(points, minAngleDeg) {
if (points.length < 4) return points.slice();
const out = [points[0]];
const minAngle = (minAngleDeg * Math.PI) / 180;
for (let i = 1; i < points.length - 1; i++) {
const a = out[out.length - 1];
const b = points[i];
const c = points[i + 1];
const abx = b.x - a.x;
const aby = b.y - a.y;
const bcx = c.x - b.x;
const bcy = c.y - b.y;
const abLen = Math.hypot(abx, aby);
const bcLen = Math.hypot(bcx, bcy);
if (abLen < 1e-6 || bcLen < 1e-6) continue;
const cos = clamp(dot(abx / abLen, aby / abLen, bcx / bcLen, bcy / bcLen), -1, 1);
const ang = Math.acos(cos);
if (ang > minAngle || state.stations.some((station) => dist(station, b) < 1)) out.push(b);
}
out.push(points[points.length - 1]);
return out;
}
function nearestSegmentIndex(points, p) {
const n = points.length;
if (n < 2) return { idx: -1, t: 0, d2: Infinity };
let best = { idx: -1, t: 0, d2: Infinity };
for (let i = 0; i < n; i++) {
const a = points[i];
const b = points[(i + 1) % n];
const abx = b.x - a.x;
const aby = b.y - a.y;
const apx = p.x - a.x;
const apy = p.y - a.y;
const abLen2 = abx * abx + aby * aby;
const t = abLen2 < 1e-6 ? 0 : clamp((apx * abx + apy * aby) / abLen2, 0, 1);
const px = a.x + abx * t;
const py = a.y + aby * t;
const dx = p.x - px;
const dy = p.y - py;
const d2 = dx * dx + dy * dy;
if (d2 < best.d2) best = { idx: i, t, d2 };
}
return best;
}
function pointSegDistance2(p, a, b) {
const abx = b.x - a.x;
const aby = b.y - a.y;
const apx = p.x - a.x;
const apy = p.y - a.y;
const abLen2 = abx * abx + aby * aby;
const t = abLen2 < 1e-6 ? 0 : clamp((apx * abx + apy * aby) / abLen2, 0, 1);
const px = a.x + abx * t;
const py = a.y + aby * t;
const dx = p.x - px;
const dy = p.y - py;
return dx * dx + dy * dy;
}
function insideCanvas(p, w, h) {
return p.x >= 0 && p.x <= w && p.y >= 0 && p.y <= h;
}
function fitCanvasToDisplay(canvas) {
const rect = canvas.getBoundingClientRect();
canvasScale = canvas.width / Math.max(1, rect.width);
// Keep internal resolution stable but match display ratio via CSS.
// We still use fixed pixel coordinates for gameplay.
return { rect };
}
function canvasToWorld(canvas, clientX, clientY) {
const rect = canvas.getBoundingClientRect();
const x = ((clientX - rect.left) / rect.width) * canvas.width;
const y = ((clientY - rect.top) / rect.height) * canvas.height;
return { x, y };
}
// --- Game state
const canvas = /** @type {HTMLCanvasElement} */ (document.getElementById("game"));
const ctx = /** @type {CanvasRenderingContext2D} */ (canvas.getContext("2d", { alpha: true }));
let storage;
try { storage = window.localStorage; } catch { /* Session-only records are supported. */ }
let records = readRecords(storage);
let unsavedRecords = null;
let selectedStation = 0;
let focusedEdge = 0;
let lastCargoKey = "";
let cargoDirty = true;
let nextCargoUpdateAtMs = 0;
let soundEnabled = false;
let audioContext = null;
let tutorialPausedRun = false;
const events = [];
const effects = [];
const ui = Object.fromEntries([
"btnDaily", "bestScore", "seedBadge", "phaseLabel", "routeStatus", "routeLength", "routeCoverage",
"btnUndo", "btnCloseLoop", "btnSuggest", "stationPicker", "cargoStatus", "dispatchFeed", "btnSound",
"statDelivered", "statMissed",
].map((id) => [id, document.getElementById(id)]));
const contractElements = Object.fromEntries(COLORS.map((color) => [color.id, document.getElementById(`contract-${color.id}`)]));
function setText(element, value) {
if (element.textContent !== value) element.textContent = value;
}
function phaseText() {
switch (mode) {
case "draw": return state.loop ? "READY TO DISPATCH" : "PLAN YOUR ROUTE";
case "over": return "SHIFT COMPLETE";
case "paused": return "DISPATCH PAUSED";
case "splice": return "REWIRE THE ROUTE";
default: return "COURIER IN TRANSIT";
}
}
function routeStatusText() {
if (state.loop) return state.route.hasContract ? "Your loop is ready" : "Connect a matching pair";
if (state.draw.points.length) return `${state.draw.points.length} stops drawn · close your loop`;
return "Every delivery starts with a line.";
}
function playTone(kind) {
if (!soundEnabled || !audioContext) return;
const oscillator = audioContext.createOscillator();
const gain = audioContext.createGain();
const time = audioContext.currentTime;
oscillator.type = "sine";
oscillator.frequency.setValueAtTime(kind === "delivery" ? 660 : kind === "pickup" ? 440 : 180, time);
oscillator.frequency.exponentialRampToValueAtTime(kind === "delivery" ? 990 : 220, time + 0.12);
gain.gain.setValueAtTime(0.055, time);
gain.gain.exponentialRampToValueAtTime(0.001, time + 0.2);
oscillator.connect(gain);
gain.connect(audioContext.destination);
oscillator.start(time);
oscillator.stop(time + 0.21);
oscillator.onended = () => { oscillator.disconnect(); gain.disconnect(); };
}
function logEvent(message, kind = "info") {
events.unshift({ message, kind });
events.splice(4);
ui.dispatchFeed.replaceChildren(...events.map((event) => {
const item = document.createElement("li");
item.className = `event-${event.kind}`;
item.textContent = event.message;
return item;
}));
}
const elScore = document.getElementById("statScore");
const elCombo = document.getElementById("statCombo");
const elTime = document.getElementById("statTime");
const elSplices = document.getElementById("statSplices");
const elRoute = document.getElementById("statRoute");
const elHint = document.getElementById("hint");
const elAccessibleState = document.getElementById("accessibleState");
const elSeed = /** @type {HTMLInputElement} */ (document.getElementById("seedInput"));
const btnNewSeed = document.getElementById("btnNewSeed");
const btnCopyLink = document.getElementById("btnCopyLink");
const btnTutorial = document.getElementById("btnTutorial");
const btnFullscreen = document.getElementById("btnFullscreen");
const btnResetLoop = document.getElementById("btnResetLoop");
const btnStart = document.getElementById("btnStart");
const btnSplice = document.getElementById("btnSplice");
const btnPause = document.getElementById("btnPause");
const modal = document.getElementById("modal");
const modalTitle = document.getElementById("modalTitle");
const modalBody = document.getElementById("modalBody");
const btnModalPrimary = document.getElementById("btnModalPrimary");
const btnModalSecondary = document.getElementById("btnModalSecondary");
const btnModalReplan = document.getElementById("btnModalReplan");
const tutorialDock = document.getElementById("tutorialDock");
const tutorialTitle = document.getElementById("tutorialTitle");
const tutorialStep = document.getElementById("tutorialStep");
const tutorialBody = document.getElementById("tutorialBody");
const btnTutSkip = document.getElementById("btnTutSkip");
const btnTutNext = document.getElementById("btnTutNext");
/** @type {"draw"|"run"|"splice"|"paused"|"over"} */
let mode = "draw";
let pausedMode = "run";
let tutorialIndex = 0;
let lastAccessibleKey = "";
let focusBeforeOverlay = null;
const TUTORIAL_STEPS = [
{
title: "Connect the network",
body: "Circles are pickups; squares are dropoffs. Connect a same-color pair in a loop of at least three points, or try Starter route. Undo reopens a loop. On the map, arrows select stations, Space adds one, and C closes the route.",
target: canvas,
},
{
title: "Dispatch the courier",
body: "Dispatch unlocks when a color contract is connected. New orders use connected stations only. More connected colors earn bigger delivery bonuses. Your courier carries up to three packages.",
target: btnStart,
},
{
title: "Splice under pressure",
body: "Press S or Splice, then choose two non-adjacent edges on a route with four or more points. On the focused map, arrows select an edge and Space confirms it. Escape or Cancel splice exits. A splice must keep at least one contract. Cargo chips show each parcel’s destination and time left.",
target: btnSplice,
},
{
title: "Beat the mutation clock",
body: "Tolls drain score and jams slow the courier. Space pauses during a run. Daily city is shared worldwide on UTC time; your best scores stay on this device. Every retry resets the city and its timers.",
target: btnPause,
},
];
/** @type {{loop: null | ReturnType<typeof buildLoop>, route: any, draw: {points: {x:number,y:number}[], dragging:boolean, cursor: null | {x:number,y:number}}, splice: {edgeA: null | number}, rng: () => number, seed: string, round: number, roundEndAtMs: number, roundDurationS: number, score: number, combo: number, delivered: number, missed: number, splicesLeft: number, maxSplices: number, bot: {segIndex: number, segPos: number, speed: number, pos: {x:number,y:number}}, stations: any[], packages: any[], nextSpawnAtMs: number, baseDeadlineS: number, cargoCap: number, cargoIds: number[], hazards: any[], nextMutationAtMs: number, difficulty: number }} */
const state = {
loop: null,
route: {
stationOnRoute: [],
pickupsCovered: 0,
dropsCovered: 0,
pickupsTotal: 0,
dropsTotal: 0,
pickupsByColor: {},
dropsByColor: {},
contractColors: [],
hasContract: false,
},
draw: { points: [], dragging: false, cursor: null },
splice: { edgeA: null },
rng: createRng(""),
seed: "",
round: 1,
roundEndAtMs: 0,
roundDurationS: 120,
score: 0,
combo: 0,
bestCombo: 0,
delivered: 0,
missed: 0,
splicesLeft: 3,
maxSplices: 3,
bot: { segIndex: 0, segPos: 0, speed: 160, pos: { x: canvas.width / 2, y: canvas.height / 2 } },
stations: [],
packages: [],
nextSpawnAtMs: 0,
baseDeadlineS: 22,
cargoCap: 3,
cargoIds: [],
hazards: [],
nextMutationAtMs: 0,
difficulty: 1,
};
let pkgIdCounter = 1;
function minDist2ToLoop(loop, p) {
let best = Infinity;
for (const seg of loop.segments) {
const d2 = pointSegDistance2(p, seg.a, seg.b);
if (d2 < best) best = d2;
}
return best;
}
function computeRouteInfo(loop) {
const stationOnRoute = [];
const pickupsByColor = {};
const dropsByColor = {};
for (const c of COLORS) {
pickupsByColor[c.id] = [];
dropsByColor[c.id] = [];
}
let pickupsTotal = 0;
let dropsTotal = 0;
let pickupsCovered = 0;
let dropsCovered = 0;
const r2 = SERVICE_RADIUS * SERVICE_RADIUS;
for (let i = 0; i < state.stations.length; i++) {
const s = state.stations[i];
if (s.kind === "pickup") pickupsTotal++;
else dropsTotal++;
let onRoute = false;
if (loop) {
const d2 = minDist2ToLoop(loop, s);
onRoute = d2 <= r2;
}
stationOnRoute.push(onRoute);
if (onRoute) {
if (s.kind === "pickup") {
pickupsCovered++;
pickupsByColor[s.colorId].push(s);
} else {
dropsCovered++;
dropsByColor[s.colorId].push(s);
}
}
}
const contractColors = COLORS.filter(
(c) => pickupsByColor[c.id].length > 0 && dropsByColor[c.id].length > 0,
).map((c) => c.id);
return {
stationOnRoute,
pickupsCovered,
dropsCovered,
pickupsTotal,
dropsTotal,
pickupsByColor,
dropsByColor,
contractColors,
hasContract: contractColors.length > 0,
};
}
function recomputeRouteInfo() {
cargoDirty = true;
const points = state.draw.points;
const preview = !state.loop && points.length > 1 ? buildLoop(points) : null;
if (preview) preview.segments.pop();
state.route = computeRouteInfo(state.loop || preview);
updateButtons();
}
function setHint(msg) {
elHint.textContent = msg;
}
function clearTutorialPulse() {
canvas.classList.remove("canvas-focus");
for (const step of TUTORIAL_STEPS) step.target.classList.remove("pulse");
}
function renderTutorialStep() {
const step = TUTORIAL_STEPS[tutorialIndex];
clearTutorialPulse();
tutorialTitle.textContent = step.title;
tutorialStep.textContent = `${tutorialIndex + 1}/${TUTORIAL_STEPS.length}`;
tutorialBody.textContent = step.body;
btnTutNext.textContent = tutorialIndex === TUTORIAL_STEPS.length - 1 ? "Start routing" : "Next";
step.target.classList.add(step.target === canvas ? "canvas-focus" : "pulse");
}
function setTutorialDone() {
try {
localStorage.setItem(TUTORIAL_DONE_KEY, "true");
} catch {
// The tutorial remains usable when storage is unavailable.
}
}
function hasCompletedTutorial() {
try {
return localStorage.getItem(TUTORIAL_DONE_KEY) === "true";
} catch {
return false;
}
}
function showTutorial(index = 0) {
tutorialPausedRun = mode === "run" || mode === "splice";
if (tutorialPausedRun) pauseToggle();
if (mode === "over") {
tutorialPausedRun = false;
return;
}
tutorialIndex = clamp(index, 0, TUTORIAL_STEPS.length - 1);
focusBeforeOverlay = document.activeElement;
tutorialDock.classList.remove("hidden");
btnTutorial.setAttribute("aria-expanded", "true");
renderTutorialStep();
updateButtons();
btnTutNext.focus();
tutorialDock.scrollIntoView({ block: "nearest" });
}
function hideTutorial({ remember = false, restoreFocus = true } = {}) {
if (tutorialDock.classList.contains("hidden")) return;
tutorialDock.classList.add("hidden");
btnTutorial.setAttribute("aria-expanded", "false");
clearTutorialPulse();
if (remember) setTutorialDone();
if (tutorialPausedRun && mode === "paused") pauseToggle();
tutorialPausedRun = false;
updateButtons();
if (restoreFocus) {
const target = focusBeforeOverlay instanceof HTMLElement && focusBeforeOverlay !== document.body ? focusBeforeOverlay : canvas;
target.focus();
}
focusBeforeOverlay = null;
}
function setMode(nextMode) {
mode = nextMode;
cargoDirty = true;
document.getElementById("app").dataset.mode = mode;
updateButtons();
if (mode === "draw") {
setHint("Draw a closed loop around pickups/dropoffs. Close by clicking near the first point.");
} else if (mode === "run") {
setHint("Deliver fast. Press S to splice (click 2 edges).");
} else if (mode === "splice") {
setHint("Pick two non-adjacent edges. On the map: arrows choose an edge, Space selects. Esc or Cancel splice exits.");
} else if (mode === "paused") {
setHint("Paused. Press Space to resume.");
}
}
function pauseToggle() {
if (!tutorialDock.classList.contains("hidden")) return;
if (mode === "paused") {
lastFrameAtMs = performance.now();
setMode(pausedMode);
} else if (mode === "run" || mode === "splice") {
syncLiveTime();
if (mode !== "run" && mode !== "splice") return;
pausedMode = mode;
setMode("paused");
}
}
function updateButtons() {
const hasLoop = !!state.loop;
const canStart = hasLoop && state.route.hasContract && mode === "draw";
btnStart.disabled = !canStart;
btnSplice.disabled = !hasLoop || state.loop.points.length < 4 || !["run", "splice"].includes(mode) || state.splicesLeft <= 0;
setText(btnSplice, mode === "splice" ? "Cancel splice" : "Splice route");
btnResetLoop.disabled = mode !== "draw" || (!hasLoop && !state.draw.points.length);
ui.btnUndo.disabled = mode !== "draw" || (!hasLoop && !state.draw.points.length);
ui.btnCloseLoop.disabled = mode !== "draw" || hasLoop || state.draw.points.length < 3;
ui.btnSuggest.disabled = mode !== "draw" || hasLoop || state.draw.points.length > 0;
for (const button of ui.stationPicker.querySelectorAll("button")) button.disabled = mode !== "draw" || hasLoop;
btnPause.disabled = mode === "draw" || mode === "over" || !tutorialDock.classList.contains("hidden");
btnPause.textContent = mode === "paused" ? "Resume" : "Pause";
btnPause.setAttribute("aria-pressed", String(mode === "paused"));
btnSplice.setAttribute("aria-pressed", String(mode === "splice"));
}
function setSeed(seedStr) {
state.seed = seedStr;
elSeed.value = seedStr;
state.rng = createRng(seedStr);
state.stations = generateStations(state.rng);
state.hazards = [];
state.nextMutationAtMs = Infinity;
ui.seedBadge.textContent = seedStr === dailySeed() ? "DAILY CITY · UTC" : "CUSTOM CITY";
const best = bestForSeed(records, seedStr);
ui.bestScore.textContent = best ? String(best.score) : "—";
selectedStation = 0;
ui.stationPicker.replaceChildren(...state.stations.map((station, index) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = `${stationLabel(index)} ${station.kind === "pickup" ? "○" : "□"}`;
button.dataset.color = station.colorId;
button.setAttribute("aria-label", `${getColor(station.colorId).label} ${station.kind === "pickup" ? "pickup" : "dropoff"} ${index % 4 + 1}, add to route`);
button.addEventListener("click", () => addStation(index));
return button;
}));
state.difficulty = 1;
recomputeRouteInfo();
}
function parseSeedFromUrl() {
const url = new URL(window.location.href);
const s = url.searchParams.get("seed");
if (s && s.trim()) return s.trim();
return dailySeed();
}
function randomSeed(rng) {
const a = Math.floor(rng() * 1e9)
.toString(36)
.toUpperCase();
const b = Math.floor(rng() * 1e9)
.toString(36)
.toUpperCase();
return `${a}-${b}`;
}
function resetRun({ keepLoop = true } = {}) {
simulationClock.reset();
lastFrameAtMs = performance.now();
state.score = 0;
state.combo = 0;
state.bestCombo = 0;
state.delivered = 0;
state.missed = 0;
state.round = 1;
state.maxSplices = 3;
state.splicesLeft = state.maxSplices;
state.baseDeadlineS = 22;
state.cargoCap = 3;
state.cargoIds = [];
state.packages = [];
pkgIdCounter = 1;
events.length = 0;
effects.length = 0;
state.splice.edgeA = null;
state.roundEndAtMs = 0;
// Regenerate the same city to restore the post-city RNG position on every attempt.
setSeed(state.seed);
logEvent("City ready. Connect matching stations.");
if (!keepLoop) {
state.loop = null;
state.draw.points = [];
state.draw.dragging = false;
state.draw.cursor = null;
recomputeRouteInfo();
setMode("draw");
return;
}
if (state.loop) {
state.bot.segIndex = 0;
state.bot.segPos = 0;
const seg = state.loop.segments[0];
state.bot.pos = { x: seg.a.x, y: seg.a.y };
}
if (!state.loop || !state.route.hasContract) {
setMode("draw");
setHint("This loop does not connect a same-color pickup and dropoff. Reset it and redraw the route.");
return;
}
startRound();
}
function startRound() {
hideTutorial({ restoreFocus: false });
const t = nowMs();
state.roundDurationS = 120;
state.roundEndAtMs = t + state.roundDurationS * 1000;
state.nextSpawnAtMs = t + 1000;
state.nextMutationAtMs = t + 16000;
state.splicesLeft = state.maxSplices;
setMode("run");
logEvent("Courier dispatched. Two minutes on the clock.");
}
function endRun() {
setMode("over");
const result = { score: Math.floor(state.score), delivered: state.delivered, missed: state.missed, bestCombo: state.bestCombo };
const saved = saveResult(storage, state.seed, result, unsavedRecords);
records = saved.records;
unsavedRecords = saved.persisted ? null : records;
ui.bestScore.textContent = String(saved.best.score);
const rank = rankForResult(result);
showModal(saved.isPersonalBest ? "New personal best" : "Shift complete", "");
const score = document.createElement("div");
score.className = "result-score";
score.textContent = `${result.score} pts`;
const title = document.createElement("p");
title.className = "result-rank";
title.textContent = rank.label;
const grid = document.createElement("div");
grid.className = "result-grid";
for (const [label, value] of [["Delivered", result.delivered], ["Missed", result.missed], ["Best combo", result.bestCombo], ["City best", saved.best.score]]) {
const cell = document.createElement("div");
const number = document.createElement("strong");
number.textContent = String(value);
const caption = document.createElement("span");
caption.textContent = label;
cell.append(number, caption);
grid.append(cell);
}
const note = document.createElement("p");
note.className = "result-note";
note.textContent = `${rank.detail} City ${state.seed}. ${saved.persisted ? "Best saved on this device." : "Storage unavailable; this result is session only."} Retry starts a fresh attempt on your final route.`;
modalBody.replaceChildren(score, title, grid, note);
logEvent(`Shift complete · ${result.score} points`, "delivery");
}
function showModal(title, body) {
focusBeforeOverlay = document.activeElement;
modalTitle.textContent = title;
modalBody.textContent = body;
modal.classList.remove("hidden");
btnModalPrimary.focus({ preventScroll: true });
}
function hideModal({ restoreFocus = false } = {}) {
modal.classList.add("hidden");
if (restoreFocus && focusBeforeOverlay instanceof HTMLElement) focusBeforeOverlay.focus({ preventScroll: true });
focusBeforeOverlay = null;
}
function generateStations(rng) {
return generateCityStations(rng, {
width: canvas.width,
height: canvas.height,
colorIds: COLORS.map((color) => color.id),
});
}
function getColor(colorId) {
const c = COLORS.find((x) => x.id === colorId);
return c || COLORS[0];
}
function findNearestStation(p, kind) {
let best = null;
let bestD = Infinity;
for (const s of state.stations) {
if (s.kind !== kind) continue;
const d = dist(p, s);
if (d < bestD) {
bestD = d;
best = s;
}
}
return best;
}
function spawnPackage() {
const rng = state.rng;
const pickups = state.route.contractColors.flatMap((id) => state.route.pickupsByColor[id]);
if (!pickups.length) return;
const pick = choice(rng, pickups);
const drops = state.route.dropsByColor[pick.colorId];
const drop = choice(rng, drops);
const deadlineS = Math.max(8, state.baseDeadlineS - state.difficulty * 0.9 + randRange(rng, -2, 3));
const createdAtMs = nowMs();
const pkg = {
id: pkgIdCounter++,
colorId: pick.colorId,
pickup: { x: pick.x, y: pick.y },
drop: { x: drop.x, y: drop.y },
createdAtMs,
expiresAtMs: createdAtMs + deadlineS * 1000,
picked: false,
delivered: false,
missed: false,
carried: false,
};
state.packages.push(pkg);
cargoDirty = true;
logEvent(`${getColor(pkg.colorId).label} order · ${Math.ceil(deadlineS)}s to deliver`);
}
function mutateCity() {
const rng = state.rng;
const kind = rng() < 0.6 ? "toll" : "jam";
const margin = 70;
const p = { x: randRange(rng, margin, canvas.width - margin), y: randRange(rng, margin, canvas.height - margin) };
if (kind === "toll") {
state.hazards.push({
kind: "toll",
x: p.x,
y: p.y,
r: randRange(rng, 26, 42),
cost: randRange(rng, 4, 9) * state.difficulty,
bornAtMs: nowMs(),
});
setHint("City mutation: toll bubble spawned. Splice your loop to dodge it.");
} else {
state.hazards.push({
kind: "jam",
x: p.x,
y: p.y,
r: randRange(rng, 34, 58),
slow: randRange(rng, 0.25, 0.45),
ttlMs: randRange(rng, 18000, 26000),
bornAtMs: nowMs(),
});
setHint("City mutation: traffic jam. Passing through slows you down.");
}
logEvent(kind === "toll" ? "New toll zone. Watch the amber ring." : "Traffic jam. Watch the blue ring.", "warning");
// Limit hazards
if (state.hazards.length > 10) state.hazards.splice(0, state.hazards.length - 10);
state.nextMutationAtMs = nowMs() + randRange(rng, 14000, 20000);
}
function updateBot(dt) {
if (!state.loop) return;
const loop = state.loop;
if (loop.segments.length === 0) return;
// Expire jams
const now = nowMs();
state.hazards = state.hazards.filter((hz) => hz.kind !== "jam" || now - hz.bornAtMs <= hz.ttlMs);
const effects = hazardEffectsAtPoint(state.hazards, state.bot.pos, now);
const speed = state.bot.speed * (0.85 + state.difficulty * 0.02) * effects.slowMult;
let distLeft = speed * dt;
// Toll cost: charge proportionally while traversing.
if (effects.tollCost > 0) {
state.score = Math.max(0, state.score - effects.tollCost * dt);
}
while (distLeft > 0.0001) {
const curSeg = loop.segments[state.bot.segIndex];
const remain = curSeg.len - state.bot.segPos;
if (distLeft < remain) {
state.bot.segPos += distLeft;
distLeft = 0;
} else {
state.bot.segPos = 0;
distLeft -= remain;
state.bot.segIndex = (state.bot.segIndex + 1) % loop.segments.length;
}
}
const cur = loop.segments[state.bot.segIndex];
const t = clamp(state.bot.segPos / cur.len, 0, 1);
state.bot.pos = { x: lerp(cur.a.x, cur.b.x, t), y: lerp(cur.a.y, cur.b.y, t) };
}
function tryPickupAndDeliver() {
const botPos = state.bot.pos;
const pickupRadius = 18;
const deliveryRadius = 18;
// Deliver first (feels better).
for (const pkgId of state.cargoIds.slice()) {
const pkg = state.packages.find((p) => p.id === pkgId);
if (!pkg || pkg.delivered || pkg.missed) continue;
if (dist(botPos, pkg.drop) <= deliveryRadius) {
pkg.delivered = true;
cargoDirty = true;
pkg.carried = false;
state.cargoIds = state.cargoIds.filter((id) => id !== pkgId);
const base = 30 + 10 * Math.max(0, state.route.contractColors.length - 1);
state.combo = state.combo + 1;
state.bestCombo = Math.max(state.bestCombo, state.combo);
const mult = 1 + Math.min(12, state.combo) * 0.12;
state.score += base * mult;
state.delivered += 1;
effects.push({ x: pkg.drop.x, y: pkg.drop.y, text: `+${Math.round(base * mult)}`, born: nowMs(), color: "#c7f36b" });
logEvent(`${getColor(pkg.colorId).label} delivered · +${Math.round(base * mult)} · combo ${state.combo}`, "delivery");
playTone("delivery");
}
}
// Pickup (oldest first) if capacity.
if (state.cargoIds.length < state.cargoCap) {
const waiting = state.packages
.filter((p) => !p.picked && !p.delivered && !p.missed)
.sort((a, b) => a.expiresAtMs - b.expiresAtMs);
for (const pkg of waiting) {
if (state.cargoIds.length >= state.cargoCap) break;
if (dist(botPos, pkg.pickup) <= pickupRadius) {
pkg.picked = true;
cargoDirty = true;
pkg.carried = true;
state.cargoIds.push(pkg.id);
playTone("pickup");
}
}
}
}
function updatePackages() {
const now = nowMs();
for (const pkg of state.packages) {
if (pkg.delivered || pkg.missed) continue;
if (now > pkg.expiresAtMs) {
pkg.missed = true;
cargoDirty = true;
pkg.carried = false;
// Remove from cargo if it was carried.
state.cargoIds = state.cargoIds.filter((id) => id !== pkg.id);
state.missed += 1;
state.combo = 0;
state.score = Math.max(0, state.score - 18);
effects.push({ x: pkg.drop.x, y: pkg.drop.y, text: "−18", born: nowMs(), color: "#fb8299" });
logEvent(`${getColor(pkg.colorId).label} deadline missed · −18`, "warning");
playTone("miss");
// Missed deadlines add a toll bubble near the miss location to push reroutes.
state.hazards.push({
kind: "toll",
x: pkg.drop.x,
y: pkg.drop.y,
r: 34,
cost: 6 + state.difficulty * 1.2,
bornAtMs: nowMs(),
});
if (state.hazards.length > 10) state.hazards.splice(0, state.hazards.length - 10);
}
}
// Trim old delivered/missed packages for performance/clarity.
if (state.packages.length > 120) {
state.packages = state.packages.filter((p) => !p.delivered && !p.missed);
}
}
function updateSpawn() {
const now = nowMs();
if (now < state.nextSpawnAtMs) return;
spawnPackage();
const rng = state.rng;
const baseEveryMs = 2600;
const accel = clamp(1 - state.difficulty * 0.05, 0.55, 1);
const jitter = randRange(rng, -450, 650);
state.nextSpawnAtMs = now + baseEveryMs * accel + jitter;
}
function updateDifficulty() {
// Smooth ramp during the round.
const remainS = Math.max(0, (state.roundEndAtMs - nowMs()) / 1000);
const progress = 1 - remainS / state.roundDurationS;
state.difficulty = 1 + progress * 6 + (state.round - 1) * 1.5;
}
function updateCargo() {
if (!cargoDirty && nowMs() < nextCargoUpdateAtMs) return;
cargoDirty = false;
const waiting = state.packages.filter((pkg) => !pkg.picked && !pkg.delivered && !pkg.missed).length;
const parcels = state.cargoIds.map((id) => state.packages.find((pkg) => pkg.id === id)).filter(Boolean).map((pkg) => {
const destination = state.stations.findIndex((station) => station.kind === "drop" && dist(station, pkg.drop) < 0.1);
return { pkg, destination, seconds: Math.max(0, Math.ceil((pkg.expiresAtMs - nowMs()) / 1000)), unreachable: !state.route.stationOnRoute[destination] };
});
nextCargoUpdateAtMs = Math.min(Infinity, ...parcels.map(({ pkg, seconds }) => seconds > 0 ? pkg.expiresAtMs - (seconds - 1) * 1000 : Infinity));
const key = JSON.stringify([mode, waiting, parcels.map(({ pkg, destination, seconds, unreachable }) => [pkg.id, destination, seconds, unreachable])]);
if (key === lastCargoKey) return;
lastCargoKey = key;
const summary = document.createElement("span");
summary.className = "cargo-summary";
summary.textContent = mode === "draw" ? "Three parcel capacity · dispatch to begin" : `${parcels.length}/${state.cargoCap} aboard · ${waiting} waiting`;
const chips = parcels.map(({ pkg, destination, seconds, unreachable }) => {
const chip = document.createElement("span");
chip.className = "cargo-chip";
chip.dataset.color = pkg.colorId;
chip.dataset.urgent = String(seconds <= 6);
chip.dataset.unreachable = String(unreachable);
const label = destination >= 0 ? stationLabel(destination) : getColor(pkg.colorId).label;
chip.append(`→ ${label}${unreachable ? " · off route" : ""}`);
const countdown = document.createElement("span");
countdown.className = "cargo-deadline";
countdown.textContent = `${seconds}s`;
chip.append(countdown);
chip.title = `${getColor(pkg.colorId).label} parcel to ${label}, ${seconds} seconds remaining${unreachable ? ", destination off route" : ""}`;
return chip;
});
ui.cargoStatus.replaceChildren(summary, ...chips);
}
function updateHud() {
const covered = state.route.pickupsCovered + state.route.dropsCovered;
const total = state.route.pickupsTotal + state.route.dropsTotal;
setText(elScore, String(Math.floor(state.score)));
setText(elCombo, `${state.combo}×`);
setText(ui.statDelivered, String(state.delivered));
setText(ui.statMissed, String(state.missed));
setText(ui.phaseLabel, phaseText());
setText(ui.routeStatus, routeStatusText());
setText(ui.routeLength, state.loop ? `~${Math.ceil(state.loop.totalLen / (state.bot.speed * 0.87))}s / lap` : "—");
setText(ui.routeCoverage, `${covered}/${total} stations`);
updateCargo();
for (const color of COLORS) {
const count = state.route.pickupsByColor[color.id]?.length || 0;
const drops = state.route.dropsByColor[color.id]?.length || 0;
const element = contractElements[color.id];
setText(element, `${count}/2 pickups · ${drops}/2 drops`);
const connected = String(count > 0 && drops > 0);
if (element.parentElement.dataset.connected !== connected) element.parentElement.dataset.connected = connected;
}
setText(elSplices, String(state.splicesLeft));
setText(elRoute, state.loop && state.route.hasContract ? `${state.route.contractColors.length} live` : `${covered}/${total}`);
if (mode === "run" || mode === "splice" || mode === "paused") {
const t = Math.max(0, (state.roundEndAtMs - nowMs()) / 1000);
setText(elTime, fmtTime(t));
} else {
setText(elTime, mode === "draw" ? "2:00" : "0:00");
}
const accessibleKey = [
mode,
state.route.contractColors.join(","),
state.route.pickupsCovered,
state.route.dropsCovered,
state.packages.filter((pkg) => !pkg.delivered && !pkg.missed).length,
state.cargoIds.length,
state.delivered,
state.missed,
].join("|");
if (accessibleKey !== lastAccessibleKey) {
lastAccessibleKey = accessibleKey;
const contracts = state.route.contractColors.length
? `${state.route.contractColors.join(", ")} contract${state.route.contractColors.length === 1 ? "" : "s"}`
: "no complete color contract";
setText(elAccessibleState, `${mode} mode. Route has ${contracts}. ${state.cargoIds.length} packages carried, ${state.delivered} delivered, ${state.missed} missed.`);
}
}
function drawBackdrop() {
const w = canvas.width;
const h = canvas.height;
const wash = ctx.createLinearGradient(0, 0, w, h);
wash.addColorStop(0, "#111f2b");
wash.addColorStop(0.52, "#101a24");
wash.addColorStop(1, "#14222a");
ctx.fillStyle = wash;
ctx.fillRect(0, 0, w, h);
// Quiet city blocks and arterial lines make the route read like a night transit map.
ctx.save();
ctx.fillStyle = "rgba(183, 211, 230, 0.025)";
const blocks = [
[42, 44, 164, 100],
[242, 38, 210, 78],
[500, 56, 124, 118],
[706, 34, 196, 102],
[64, 196, 124, 150],
[250, 180, 178, 116],
[470, 224, 172, 122],
[724, 190, 156, 142],
[32, 416, 196, 118],
[278, 382, 150, 142],
[516, 408, 120, 110],
[714, 392, 204, 140],
];