-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1780 lines (1632 loc) · 64 KB
/
Copy pathindex.html
File metadata and controls
1780 lines (1632 loc) · 64 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Curling Ice Lab</title>
<style>
:root {
color-scheme: light;
--ink: #16202a;
--muted: #5f6d78;
--line: #cdd8df;
--panel: #f7fafc;
--ice: #eaf7fb;
--blue: #1f75bc;
--red: #d94a44;
--gold: #d9a521;
--green: #188a5b;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: var(--ink);
background: #ffffff;
}
.app {
min-height: 100vh;
display: grid;
grid-template-columns: minmax(280px, 360px) 1fr minmax(280px, 360px);
gap: 0;
}
aside {
border-right: 1px solid var(--line);
background: var(--panel);
padding: 18px;
overflow: auto;
max-height: 100vh;
}
aside:last-child {
border-right: 0;
border-left: 1px solid var(--line);
}
main {
min-width: 0;
display: grid;
grid-template-rows: auto 1fr auto;
background: linear-gradient(180deg, #ffffff, #edf8fb);
}
h1 {
font-size: 22px;
line-height: 1.12;
margin: 0 0 6px;
letter-spacing: 0;
}
h2 {
font-size: 14px;
text-transform: uppercase;
letter-spacing: .08em;
color: #304658;
margin: 22px 0 10px;
}
p {
margin: 0;
color: var(--muted);
line-height: 1.42;
font-size: 14px;
}
.topbar {
padding: 14px 18px;
border-bottom: 1px solid var(--line);
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
background: rgba(255, 255, 255, .88);
}
.status {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
color: var(--muted);
font-size: 13px;
}
.pill {
display: inline-flex;
align-items: center;
gap: 6px;
border: 1px solid var(--line);
border-radius: 999px;
padding: 6px 10px;
background: #fff;
color: #304658;
white-space: nowrap;
}
.canvas-wrap {
min-height: 520px;
padding: 16px;
display: grid;
place-items: center;
}
canvas {
width: min(100%, 920px);
height: min(76vh, 720px);
min-height: 520px;
border: 1px solid #b6ccd7;
border-radius: 8px;
background: var(--ice);
box-shadow: 0 18px 45px rgba(29, 63, 86, .12);
touch-action: none;
}
.controls {
display: grid;
gap: 14px;
}
label {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px 12px;
align-items: center;
font-size: 13px;
color: #26394a;
}
input[type="range"], label select {
grid-column: 1 / -1;
width: 100%;
accent-color: var(--blue);
}
select, button {
font: inherit;
}
select {
width: 100%;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: #fff;
color: var(--ink);
}
.value {
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.buttons {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
margin-top: 12px;
}
button {
border: 1px solid #9fb5c0;
border-radius: 8px;
padding: 10px 12px;
background: #fff;
color: #193248;
cursor: pointer;
}
button.primary {
background: #163b57;
color: #fff;
border-color: #163b57;
}
button:active {
transform: translateY(1px);
}
.readout {
display: grid;
gap: 9px;
margin-top: 12px;
}
.metric {
display: grid;
grid-template-columns: 1fr auto;
gap: 12px;
padding: 9px 0;
border-bottom: 1px solid #dce6eb;
font-size: 13px;
}
.metric strong {
font-weight: 650;
}
.metric span:last-child {
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.agent-row {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 10px;
padding: 10px 0;
border-bottom: 1px solid #dce6eb;
font-size: 13px;
}
.shot-log {
display: grid;
gap: 8px;
margin-top: 10px;
font-size: 12px;
max-height: 220px;
overflow: auto;
border-top: 1px solid #dce6eb;
padding-top: 8px;
}
.shot-entry {
display: grid;
grid-template-columns: auto 1fr;
gap: 6px 10px;
padding: 8px 0;
border-bottom: 1px solid #dce6eb;
}
.shot-entry strong {
font-size: 12px;
}
.shot-entry span {
color: var(--muted);
line-height: 1.35;
}
.dot {
width: 12px;
height: 12px;
border-radius: 50%;
background: var(--green);
}
.footer {
border-top: 1px solid var(--line);
padding: 10px 18px;
font-size: 12px;
color: var(--muted);
background: rgba(255,255,255,.82);
}
@media (max-width: 1080px) {
.app {
grid-template-columns: 1fr;
}
aside {
max-height: none;
border-right: 0;
border-bottom: 1px solid var(--line);
}
aside:last-child {
border-left: 0;
}
main {
grid-row: 1;
}
}
@media (max-width: 640px) {
.topbar {
display: grid;
}
canvas {
min-height: 460px;
height: 68vh;
}
}
</style>
</head>
<body>
<div class="app">
<aside>
<h1>Curling Ice Lab</h1>
<p>Agent-based curling simulation with physics-informed ice, sweeping, uncertainty, and shot prediction.</p>
<h2>Shot</h2>
<div class="controls" id="shotControls">
<label>Shot weight <span class="value" id="weightLabel">Draw</span>
<select id="weight">
<option value="guard">Guard</option>
<option value="draw" selected>Draw</option>
<option value="backline">Back line</option>
<option value="hack">Hack</option>
<option value="control">Control</option>
<option value="normal">Normal</option>
<option value="peel">Peel</option>
</select>
</label>
<label>Handle turn <span class="value" id="turnLabel">In-turn</span>
<select id="turn">
<option value="in" selected>In-turn / clockwise</option>
<option value="out">Out-turn / counter</option>
</select>
</label>
<label>Release speed <span class="value" data-for="speed"></span><input id="speed" type="range" min="1.8" max="4.8" value="3.25" step="0.01"></label>
<label>Line angle <span class="value" data-for="angle"></span><input id="angle" type="range" min="-8" max="8" value="3.2" step="0.1"></label>
<label>Release twist <span class="value" data-for="spin"></span><input id="spin" type="range" min="-2.5" max="2.5" value="1.1" step="0.05"></label>
<label>Hack foot <span class="value" id="hackLabel">Right hack</span>
<select id="hack">
<option value="right" selected>Right hack</option>
<option value="left">Left hack</option>
</select>
</label>
<label>Hack push <span class="value" data-for="push"></span><input id="push" type="range" min="-0.35" max="0.55" value="0.05" step="0.01"></label>
<label>Stone roughness <span class="value" data-for="roughness"></span><input id="roughness" type="range" min="0.6" max="1.6" value="1.0" step="0.01"></label>
</div>
<h2>Game Setup</h2>
<div class="controls">
<label>Play mode <span class="value" id="modeTypeLabel">Single player</span>
<select id="gameMode">
<option value="single" selected>Single player: control both</option>
<option value="local">Local multiplayer</option>
<option value="computer">Individual vs computer</option>
</select>
</label>
</div>
<div class="readout">
<div class="metric"><strong>Coin flip</strong><span id="coinResult">not flipped</span></div>
<div class="metric"><strong>Hammer</strong><span id="hammerTeam">--</span></div>
<div class="metric"><strong>End</strong><span id="endNumber">1 / 8</span></div>
<div class="metric"><strong>Score</strong><span id="scoreboard">Blue 0 - Yellow 0</span></div>
<div class="metric"><strong>Throwing now</strong><span id="currentTeam">--</span></div>
<div class="metric"><strong>Control</strong><span id="controlMode">you control both</span></div>
<div class="metric"><strong>Stone</strong><span id="shotCount">0 / 16</span></div>
<div class="metric"><strong>Shot rock</strong><span id="shotRock">none</span></div>
</div>
<h2>Ice Chemistry</h2>
<div class="controls">
<label>Ice temperature <span class="value" data-for="temperature"></span><input id="temperature" type="range" min="-7.5" max="-2.0" value="-4.6" step="0.1"></label>
<label>Humidity <span class="value" data-for="humidity"></span><input id="humidity" type="range" min="25" max="90" value="52" step="1"></label>
<label>Pebble height <span class="value" data-for="pebble"></span><input id="pebble" type="range" min="0.3" max="1.6" value="0.85" step="0.01"></label>
<label>Frost contamination <span class="value" data-for="frost"></span><input id="frost" type="range" min="0" max="1" value="0.12" step="0.01"></label>
</div>
<h2>Actions</h2>
<div class="buttons">
<button class="primary" id="throwBtn">Throw</button>
<button id="predictBtn">Predict</button>
<button id="sweepBtn">Sweep</button>
<button id="resetBtn">Reset</button>
<button id="coinBtn">Coin flip</button>
<button id="nextCallBtn">Next call</button>
<button id="nextEndBtn">Next end</button>
<button id="fullViewBtn">Full sheet</button>
<button id="houseViewBtn">House zoom</button>
<button id="saveStateBtn">Save game</button>
<button id="loadStateBtn">Load game</button>
</div>
</aside>
<main>
<div class="topbar">
<div class="status">
<span class="pill">Mode: <strong id="modeLabel">Ready</strong></span>
<span class="pill">Team: <strong id="teamPill">Blue</strong></span>
<span class="pill">Stochastic ice field: <strong id="iceSeed">seed 174</strong></span>
<span class="pill">Hybrid solver: <strong>deterministic + noise</strong></span>
</div>
<div style="display:grid; grid-template-columns: 1fr 1fr; gap: 10px;">
<select id="strategy">
<option value="guard">Guard draw</option>
<option value="button" selected>Button draw</option>
<option value="takeout">Controlled takeout</option>
</select>
<select id="camera">
<option value="full" selected>Full sheet</option>
<option value="house">House zoom</option>
<option value="delivery">Delivery zoom</option>
</select>
</div>
</div>
<div class="canvas-wrap">
<canvas id="rink" width="920" height="720" aria-label="Curling simulation rink"></canvas>
</div>
<div class="footer">
The model estimates contact melt film, pebble drag, frost, humidity, thermal drift, curl torque, sweeping heat, and random ice heterogeneity. Coefficients are tunable approximations for product prototyping.
</div>
</main>
<aside>
<h2>Predictive Simulation</h2>
<p>Runs a Monte Carlo rollout around the current shot and environment. The pale paths are likely outcomes; the solid path is the active stone.</p>
<div class="readout">
<div class="metric"><strong>Skip call</strong><span id="skipCall">Draw to 7</span></div>
<div class="metric"><strong>Broom placement</strong><span id="broomPlacement">center button</span></div>
<div class="metric"><strong>Handle lesson</strong><span id="handleLesson">turn curls toward broom</span></div>
<div class="metric"><strong>Collision model</strong><span id="collisionModel">momentum transfer</span></div>
<div class="metric"><strong>Expected stop</strong><span id="expectedStop">--</span></div>
<div class="metric"><strong>Uncertainty radius</strong><span id="uncertainty">--</span></div>
<div class="metric"><strong>Button probability</strong><span id="buttonProb">--</span></div>
<div class="metric"><strong>Mean curl</strong><span id="meanCurl">--</span></div>
</div>
<h2>Training Notes</h2>
<div class="readout">
<div class="metric"><strong>Broom + handle</strong><span id="tutorialBroom">Aim outside, curl back to target.</span></div>
<div class="metric"><strong>Weight</strong><span id="tutorialWeight">More weight curls less and hits harder.</span></div>
<div class="metric"><strong>Takeout physics</strong><span id="tutorialCollision">Nose hits remove straight; angled hits roll.</span></div>
</div>
<h2>Agents</h2>
<div class="agent-row"><span class="dot"></span><span>Sweeper A: thermal film control</span><strong id="agentA">idle</strong></div>
<div class="agent-row"><span class="dot" style="background:#37a0c8"></span><span>Sweeper B: trajectory correction</span><strong id="agentB">idle</strong></div>
<div class="agent-row"><span class="dot" style="background:#c9772d"></span><span>Ice observer: adaptive friction estimate</span><strong id="agentC">learning</strong></div>
<h2>Live Physics</h2>
<div class="readout">
<div class="metric"><strong>Velocity</strong><span id="velocity">0.00 m/s</span></div>
<div class="metric"><strong>Handle turn</strong><span id="handleTurn">clockwise</span></div>
<div class="metric"><strong>Spin</strong><span id="spinLive">0.00 rad/s</span></div>
<div class="metric"><strong>Effective friction</strong><span id="friction">0.000</span></div>
<div class="metric"><strong>Surface film</strong><span id="film">0.00</span></div>
<div class="metric"><strong>Score estimate</strong><span id="score">--</span></div>
</div>
<h2>Match Tracker</h2>
<p>Shot records save in this browser so you can review what you tried during a full match.</p>
<div class="buttons">
<button id="exportLogBtn">Export CSV</button>
<button id="clearLogBtn">Clear log</button>
</div>
<div class="readout">
<div class="metric"><strong>Logged shots</strong><span id="logCount">0</span></div>
</div>
<div class="shot-log" id="shotLog"></div>
</aside>
</div>
<script>
const canvas = document.getElementById("rink");
const ctx = canvas.getContext("2d");
const sheet = {
width: 5.0,
playingLength: 42.07,
nearTee: 3.66,
farTee: 42.07 - 3.66,
hogOffset: 6.40,
backOffset: 1.829,
house: [1.829, 1.219, 0.610, 0.152],
hackWidth: 0.152,
hackInside: 0.076,
hackLine: 0
};
const meters = { w: sheet.width, h: sheet.playingLength };
const view = { yMin: 0, yMax: sheet.playingLength };
const ui = Object.fromEntries([...document.querySelectorAll("input, select")].map(el => [el.id, el]));
const labels = Object.fromEntries([...document.querySelectorAll("[data-for]")].map(el => [el.dataset.for, el]));
const readout = id => document.getElementById(id);
const state = {
seed: 174,
running: false,
sweeping: false,
mode: "Ready",
stone: null,
path: [],
predictions: [],
stats: null,
target: { x: 0, y: sheet.farTee },
teams: {
blue: { name: "Blue", color: "#1f75bc" },
yellow: { name: "Yellow", color: "#f0c84b" }
},
hammer: "yellow",
coinFlipped: false,
endNumber: 1,
maxEnds: 8,
score: { blue: 0, yellow: 0 },
lastEndResult: null,
deliveryIndex: 0,
gameMode: "single",
humanTeam: "blue",
computerTimer: null,
stones: [],
matchLog: [],
activeShotRecord: null,
observerBias: 0
};
const weightPresets = {
guard: { label: "Guard", speed: 2.62, target: { x: 0, y: sheet.farTee - sheet.hogOffset + 2.10 } },
draw: { label: "Draw", speed: 3.25, target: { x: 0, y: sheet.farTee } },
backline: { label: "Back line", speed: 3.48, target: { x: 0, y: sheet.farTee + 0.85 } },
hack: { label: "Hack", speed: 3.82, target: { x: 0.28, y: sheet.farTee } },
control: { label: "Control", speed: 4.18, target: { x: -0.72, y: sheet.farTee - 1.5 } },
normal: { label: "Normal", speed: 4.48, target: { x: 0.64, y: sheet.farTee - 0.5 } },
peel: { label: "Peel", speed: 4.78, target: { x: 1.05, y: sheet.farTee - sheet.hogOffset + 2.4 } }
};
function val(id) {
return Number(ui[id].value);
}
function fmt(id, suffix = "") {
labels[id].textContent = `${val(id).toFixed(id === "humidity" ? 0 : 2)}${suffix}`;
}
function updateLabels() {
fmt("speed", " m/s");
fmt("angle", " deg");
fmt("spin", " rad/s");
fmt("push", " m/s");
fmt("roughness", "x");
fmt("temperature", " C");
fmt("humidity", "%");
fmt("pebble", " mm");
fmt("frost", "");
readout("weightLabel").textContent = weightPresets[ui.weight.value].label;
readout("turnLabel").textContent = ui.turn.value === "in" ? "In-turn" : "Out-turn";
readout("hackLabel").textContent = ui.hack.value === "right" ? "Right hack" : "Left hack";
readout("modeTypeLabel").textContent = modeName();
updateGamePanel();
}
function firstTeamKey() {
return state.hammer === "blue" ? "yellow" : "blue";
}
function currentTeamKey() {
const first = firstTeamKey();
if (state.deliveryIndex % 2 === 0) return first;
return first === "blue" ? "yellow" : "blue";
}
function currentTeam() {
return state.teams[currentTeamKey()];
}
function modeName() {
if (state.gameMode === "computer") return "Vs computer";
if (state.gameMode === "local") return "Local multiplayer";
return "Single player";
}
function isComputerTurn() {
return state.gameMode === "computer" && currentTeamKey() !== state.humanTeam;
}
function controlLabel() {
if (state.gameMode === "computer") return isComputerTurn() ? "computer thinking" : "your turn";
if (state.gameMode === "local") return `${currentTeam().name} player`;
return "you control both";
}
function turnSpin() {
return ui.turn.value === "in" ? Math.abs(val("spin")) : -Math.abs(val("spin"));
}
function updateGamePanel() {
const teamKey = currentTeamKey();
const team = state.teams[teamKey];
const houseState = scoreHouse();
readout("coinResult").textContent = state.coinFlipped ? `${state.teams[state.hammer].name} won hammer` : "not flipped";
readout("hammerTeam").textContent = state.teams[state.hammer].name;
readout("endNumber").textContent = `${state.endNumber} / ${state.maxEnds}`;
readout("scoreboard").textContent = `Blue ${state.score.blue} - Yellow ${state.score.yellow}`;
readout("currentTeam").textContent = `${team.name} throws${isComputerTurn() ? " (computer)" : ""}`;
readout("controlMode").textContent = controlLabel();
readout("teamPill").textContent = team.name;
readout("teamPill").style.color = team.color;
readout("shotCount").textContent = `${state.deliveryIndex} / 16`;
readout("shotRock").textContent = houseState.scoringTeam ? `${state.teams[houseState.scoringTeam].name} ${houseState.points}` : "none in house";
updateSkipCall();
updateTutorial();
}
function scoreHouse() {
const inHouse = state.stones
.map(stone => ({ ...stone, distance: Math.hypot(stone.x, stone.y - sheet.farTee) }))
.filter(stone => stone.distance <= sheet.house[0] + 0.145)
.sort((a, b) => a.distance - b.distance);
if (!inHouse.length) return { scoringTeam: null, points: 0, shot: null };
const scoringTeam = inHouse[0].team;
const blocker = inHouse.find(stone => stone.team !== scoringTeam);
const limit = blocker ? blocker.distance : Infinity;
const points = inHouse.filter(stone => stone.team === scoringTeam && stone.distance < limit).length;
return { scoringTeam, points, shot: inHouse[0] };
}
function completeEnd() {
const result = scoreHouse();
state.lastEndResult = { end: state.endNumber, ...result };
if (result.scoringTeam && result.points > 0) {
state.score[result.scoringTeam] += result.points;
state.hammer = result.scoringTeam === "blue" ? "yellow" : "blue";
state.mode = `${state.teams[result.scoringTeam].name} scores ${result.points}`;
} else {
state.mode = "Blank end";
}
state.deliveryIndex = 16;
updateGamePanel();
saveGameState();
}
function startNextEnd() {
clearComputerTimer();
if (state.running) return;
if (state.deliveryIndex < 16 && state.stones.length > 0) completeEnd();
if (state.endNumber >= state.maxEnds) {
state.mode = "Match complete";
updateGamePanel();
return;
}
state.endNumber += 1;
state.deliveryIndex = 0;
state.stones = [];
state.stone = null;
state.path = [];
state.predictions = [];
state.stats = null;
state.target = { x: 0, y: sheet.farTee };
state.mode = `End ${state.endNumber}`;
suggestNextCall();
simulatePrediction(64);
saveGameState();
scheduleComputerTurn();
}
function updateSkipCall() {
const region = regionForTarget(state.target.y);
const turn = ui.turn.value === "in" ? "in-turn" : "out-turn";
const weight = weightPresets[ui.weight.value].label.toLowerCase();
const broomX = state.target.x > 0.08 ? `${state.target.x.toFixed(1)} m right` : state.target.x < -0.08 ? `${Math.abs(state.target.x).toFixed(1)} m left` : "center";
readout("skipCall").textContent = `${currentTeam().name}: ${turn} ${weight} to ${region}`;
readout("broomPlacement").textContent = `${broomX}, ${region}`;
readout("handleLesson").textContent = ui.turn.value === "in"
? "clockwise curl works back toward the broom line"
: "counter curl works back toward the broom line";
readout("collisionModel").textContent = ui.weight.value === "control" || ui.weight.value === "normal" || ui.weight.value === "peel"
? "impact transfers normal momentum to promote or remove"
: "draw path avoids contact unless line overlaps";
}
function regionForTarget(y) {
const regions = [
[1, "1 long guard", sheet.farTee - sheet.hogOffset + 0.75],
[2, "2 mid guard", sheet.farTee - sheet.hogOffset + 2.10],
[3, "3 tight guard", sheet.farTee - sheet.hogOffset + 3.45],
[4, "4 top 12", sheet.farTee - sheet.house[0]],
[5, "5 top 8", sheet.farTee - sheet.house[1]],
[6, "6 top 4", sheet.farTee - sheet.house[2]],
[7, "7 button", sheet.farTee],
[8, "8 back 4", sheet.farTee + sheet.house[2]],
[9, "9 back 8", sheet.farTee + sheet.house[1]],
[10, "10 back 12", sheet.farTee + sheet.house[0]]
];
return regions.reduce((best, item) => Math.abs(item[2] - y) < Math.abs(best[2] - y) ? item : best)[1];
}
function seededNoise(x, y, seed = state.seed) {
const n = Math.sin(x * 91.7 + y * 37.3 + seed * 11.13) * 43758.5453;
return n - Math.floor(n);
}
function smoothNoise(x, y) {
const ix = Math.floor(x), iy = Math.floor(y);
const fx = x - ix, fy = y - iy;
const a = seededNoise(ix, iy);
const b = seededNoise(ix + 1, iy);
const c = seededNoise(ix, iy + 1);
const d = seededNoise(ix + 1, iy + 1);
const sx = fx * fx * (3 - 2 * fx);
const sy = fy * fy * (3 - 2 * fy);
return lerp(lerp(a, b, sx), lerp(c, d, sx), sy);
}
function lerp(a, b, t) { return a + (b - a) * t; }
function clamp(v, min, max) { return Math.max(min, Math.min(max, v)); }
function envAt(x, y, sweep = state.sweeping) {
const temp = val("temperature");
const humidity = val("humidity") / 100;
const pebble = val("pebble");
const frost = val("frost");
const roughness = val("roughness");
const heterogeneity = (smoothNoise(x * 1.4 + 8, y * .42) - .5) * 0.16;
const thermalPenalty = Math.abs(temp + 4.7) * 0.006;
const meltFilm = clamp(0.48 + (temp + 5.2) * 0.095 + humidity * 0.18 + (sweep ? 0.24 : 0), 0.05, 0.95);
const frostDrag = frost * (0.011 + humidity * 0.008);
const pebbleDrag = 0.010 + pebble * 0.007 + Math.max(0, pebble - 1.1) * 0.007;
const filmReduction = meltFilm * 0.006;
const mu = clamp((pebbleDrag + frostDrag + thermalPenalty - filmReduction + heterogeneity * 0.010) * roughness + state.observerBias, 0.006, 0.055);
const anisotropy = (smoothNoise(x * .8, y * .8 + 22) - .5) * 0.026 + frost * 0.012;
return { mu, meltFilm, anisotropy, heterogeneity };
}
function makeStone(variance = 0) {
const angle = (val("angle") + randomNormal() * variance * 1.2) * Math.PI / 180;
const hackX = ui.hack.value === "right" ? sheet.hackInside + sheet.hackWidth / 2 : -(sheet.hackInside + sheet.hackWidth / 2);
const speed = Math.max(0.2, val("speed") + val("push") + randomNormal() * variance * 0.11);
const spin = turnSpin() + randomNormal() * variance * 0.14;
return {
x: hackX,
y: 0.35,
vx: Math.sin(angle) * speed,
vy: Math.cos(angle) * speed,
omega: spin,
color: currentTeam().color,
team: currentTeamKey(),
handleAngle: spin >= 0 ? 0.75 : -0.75,
stopped: false
};
}
function randomNormal() {
let u = 0, v = 0;
while (u === 0) u = Math.random();
while (v === 0) v = Math.random();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
function stepStone(stone, dt, opts = {}) {
if (stone.stopped) return;
const speed = Math.hypot(stone.vx, stone.vy);
if (speed < 0.035 || stone.y > meters.h - .3 || Math.abs(stone.x) > meters.w / 2 + .8) {
stone.stopped = true;
stone.vx = 0;
stone.vy = 0;
stone.omega = 0;
return;
}
const e = envAt(stone.x, stone.y, opts.sweep ?? shouldSweep(stone));
const g = 9.81;
const drag = e.mu * g;
const nx = stone.vx / speed;
const ny = stone.vy / speed;
const curlSign = Math.sign(stone.omega || 1);
const curlForce = curlSign * (0.012 + Math.abs(stone.omega) * 0.011) * (1 - e.meltFilm * .22);
const lateral = curlForce + e.anisotropy;
const processNoise = opts.noise ? (Math.random() - .5) * opts.noise : 0;
stone.vx += (-nx * drag + -ny * lateral + processNoise) * dt;
stone.vy += (-ny * drag + nx * lateral) * dt;
stone.omega *= Math.max(0, 1 - (0.13 + e.mu * 1.6) * dt);
stone.handleAngle += stone.omega * dt;
stone.x += stone.vx * dt;
stone.y += stone.vy * dt;
const collisionStones = opts.stones || state.stones;
for (const other of collisionStones) {
resolveCollision(stone, other);
}
}
function resolveCollision(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
const dist = Math.max(0.001, Math.hypot(dx, dy));
const diameter = 0.29;
if (dist >= diameter) return false;
const nxHit = dx / dist;
const nyHit = dy / dist;
const overlap = diameter - dist;
a.x += nxHit * overlap * 0.52;
a.y += nyHit * overlap * 0.52;
b.x -= nxHit * overlap * 0.48;
b.y -= nyHit * overlap * 0.48;
const avx = a.vx || 0;
const avy = a.vy || 0;
const bvx = b.vx || 0;
const bvy = b.vy || 0;
const relVx = avx - bvx;
const relVy = avy - bvy;
const impactSpeed = relVx * nxHit + relVy * nyHit;
if (impactSpeed > 0) return true;
const restitution = 0.78;
const impulse = -impactSpeed * (1 + restitution) * 0.5;
a.vx = avx + impulse * nxHit;
a.vy = avy + impulse * nyHit;
b.vx = bvx - impulse * nxHit * 0.98;
b.vy = bvy - impulse * nyHit * 0.98;
const tangentSpeed = -relVx * nyHit + relVy * nxHit;
const roll = tangentSpeed * 0.07;
a.vx += nyHit * roll;
a.vy += -nxHit * roll;
b.vx += -nyHit * roll;
b.vy += nxHit * roll;
a.omega = (a.omega || 0) * 0.68;
b.handleAngle = (b.handleAngle || 0) + roll * 0.4;
return true;
}
function stepFieldStones(dt, stones = state.stones) {
for (const stone of stones) {
const speed = Math.hypot(stone.vx || 0, stone.vy || 0);
if (speed < 0.025) {
stone.vx = 0;
stone.vy = 0;
continue;
}
const e = envAt(stone.x, stone.y, false);
const drag = e.mu * 9.81;
stone.vx -= (stone.vx / speed) * drag * dt;
stone.vy -= (stone.vy / speed) * drag * dt;
stone.x += stone.vx * dt;
stone.y += stone.vy * dt;
stone.x = clamp(stone.x, -meters.w / 2 - .4, meters.w / 2 + .4);
stone.y = clamp(stone.y, 0, meters.h);
stone.handleAngle = (stone.handleAngle || 0) + speed * dt * 0.35;
}
for (let i = 0; i < stones.length; i++) {
for (let j = i + 1; j < stones.length; j++) {
resolveCollision(stones[i], stones[j]);
}
}
if (stones === state.stones) {
state.stones = state.stones.filter(stone => stone.y >= 0 && stone.y <= meters.h && Math.abs(stone.x) <= meters.w / 2 + 0.7);
}
}
function shouldSweep(stone) {
if (!state.sweeping) return false;
const targetY = state.target.y;
const speed = Math.hypot(stone.vx, stone.vy);
const stoppingDistance = speed * speed / Math.max(0.04, 2 * envAt(stone.x, stone.y, false).mu * 9.81);
const projectedY = stone.y + stoppingDistance;
return projectedY < targetY + 0.8 && Math.abs(stone.x) < 1.5;
}
function simulatePrediction(samples = 72) {
const predictions = [];
const stops = [];
for (let i = 0; i < samples; i++) {
const stone = makeStone(1);
const fieldStones = state.stones.map(s => ({ ...s }));
const path = [];
let steps = 0;
for (let t = 0; t < 42 && !stone.stopped; t += 0.035) {
stepStone(stone, 0.035, { sweep: strategySweep(stone), noise: 0.004, stones: fieldStones });
stepFieldStones(0.035, fieldStones);
if (steps % 3 === 0) path.push({ x: stone.x, y: stone.y });
steps++;
}
predictions.push(path);
stops.push({ x: stone.x, y: stone.y });
}
const mean = stops.reduce((a, p) => ({ x: a.x + p.x / stops.length, y: a.y + p.y / stops.length }), { x: 0, y: 0 });
const spread = Math.sqrt(stops.reduce((s, p) => s + ((p.x - mean.x) ** 2 + (p.y - mean.y) ** 2), 0) / stops.length);
const buttonProb = stops.filter(p => Math.hypot(p.x - state.target.x, p.y - state.target.y) < 0.61).length / stops.length;
const meanCurl = stops.reduce((s, p) => s + p.x, 0) / stops.length;
state.predictions = predictions;
state.stats = { mean, spread, buttonProb, meanCurl };
updateStats();
}
function strategySweep(stone) {
const mode = ui.strategy.value;
if (mode === "takeout") return stone.y < 29 && Math.abs(stone.x) < .9;
if (mode === "guard") return stone.y < 28;
return shouldSweep(stone);
}
function updateStats() {
if (!state.stats) return;
readout("expectedStop").textContent = `${state.stats.mean.x.toFixed(2)} m, ${state.stats.mean.y.toFixed(2)} m`;
readout("uncertainty").textContent = `${state.stats.spread.toFixed(2)} m`;
readout("buttonProb").textContent = `${Math.round(state.stats.buttonProb * 100)}%`;
readout("meanCurl").textContent = `${state.stats.meanCurl.toFixed(2)} m`;
}
function storageGet(key) {
try {
if (typeof localStorage === "undefined") return null;
return localStorage.getItem(key);
} catch {
return null;
}
}
function storageSet(key, value) {
try {
if (typeof localStorage !== "undefined") localStorage.setItem(key, value);
} catch {
// Browser storage can be unavailable in some preview modes; keep the in-memory log.
}
}
function loadMatchLog() {
try {
state.matchLog = JSON.parse(storageGet("curlingMatchLog") || "[]");
} catch {
state.matchLog = [];
}
renderMatchLog();
}
function saveMatchLog() {
storageSet("curlingMatchLog", JSON.stringify(state.matchLog));
renderMatchLog();
}
function createShotRecord(stone) {
return {
id: crypto.randomUUID ? crypto.randomUUID() : String(Date.now()),
end: state.endNumber,
shot: state.deliveryIndex + 1,
team: currentTeam().name,
hammer: state.teams[state.hammer].name,
strategy: ui.strategy.value,
weight: weightPresets[ui.weight.value].label,
turn: ui.turn.value === "in" ? "in-turn / clockwise" : "out-turn / counter",
hack: ui.hack.value,
speed: val("speed"),
push: val("push"),
twist: turnSpin(),
broomX: state.target.x,
broomY: state.target.y,
expectedX: state.stats?.mean.x ?? null,
expectedY: state.stats?.mean.y ?? null,
uncertainty: state.stats?.spread ?? null,
buttonProbability: state.stats?.buttonProb ?? null,
releaseX: stone.x,
releaseY: stone.y,
finalX: null,
finalY: null,
score: null,
result: "in progress",
time: new Date().toISOString()
};
}
function finishShotRecord(stone) {
if (!state.activeShotRecord) return;
const d = Math.hypot(stone.x - state.target.x, stone.y - state.target.y);
state.activeShotRecord.finalX = stone.x;
state.activeShotRecord.finalY = stone.y;
state.activeShotRecord.score = Math.max(0, 100 - d * 44);
state.activeShotRecord.error = state.activeShotRecord.expectedX === null
? null
: Math.hypot(stone.x - state.activeShotRecord.expectedX, stone.y - state.activeShotRecord.expectedY);
state.activeShotRecord.region = regionForTarget(stone.y);
state.activeShotRecord.result = `${stone.x.toFixed(2)} m, ${stone.y.toFixed(2)} m`;
state.matchLog.unshift(state.activeShotRecord);
state.activeShotRecord = null;
saveMatchLog();
}
function renderMatchLog() {
const log = readout("shotLog");
if (!log) return;
readout("logCount").textContent = String(state.matchLog.length);
log.innerHTML = "";
if (!state.matchLog.length) {
log.innerHTML = "<p>No shots logged yet.</p>";
return;
}
for (const item of state.matchLog.slice(0, 12)) {
const row = document.createElement("div");
row.className = "shot-entry";
const errorText = item.error === null || item.error === undefined ? "prediction --" : `miss ${Number(item.error).toFixed(2)} m`;
const scoreText = item.score === null || item.score === undefined ? "" : `, score ${Number(item.score).toFixed(0)}/100`;
row.innerHTML = `
<strong>E${item.end || 1} #${item.shot}</strong>
<span>${item.team}: ${item.weight}, ${item.turn}, ${item.hack} hack<br>
broom ${regionForTarget(Number(item.broomY))} ${formatPoint(item.broomX, item.broomY)} -> ${item.region || "stop"} ${formatPoint(item.finalX, item.finalY)}<br>
${errorText}${scoreText}</span>
`;
log.appendChild(row);
}
}