-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
1039 lines (896 loc) · 40.8 KB
/
game.js
File metadata and controls
1039 lines (896 loc) · 40.8 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
/* ─────────────────────────────────────────────
Data Quality Duel
game.js
───────────────────────────────────────────── */
'use strict';
// ─── SVG art generator ────────────────────────────────────────────────────────
// Each operator gets a unique orbital-mechanics SVG illustration
const CARD_ART = {
value: `<svg viewBox="0 0 180 90" xmlns="http://www.w3.org/2000/svg">
<ellipse cx="90" cy="45" rx="70" ry="30" fill="none" stroke="rgba(255,255,255,0.5)" stroke-width="1"/>
<ellipse cx="90" cy="45" rx="45" ry="18" fill="none" stroke="rgba(255,255,255,0.3)" stroke-width="1"/>
<circle cx="90" cy="45" r="5" fill="#F59E0B"/>
<circle cx="158" cy="43" r="4" fill="#10B981"/>
<line x1="90" y1="15" x2="90" y2="75" stroke="rgba(255,255,255,0.15)" stroke-width="0.5"/>
<line x1="20" y1="45" x2="160" y2="45" stroke="rgba(255,255,255,0.15)" stroke-width="0.5"/>
</svg>`,
column: `<svg viewBox="0 0 180 90" xmlns="http://www.w3.org/2000/svg">
<ellipse cx="90" cy="45" rx="72" ry="32" fill="none" stroke="rgba(255,255,255,0.5)" stroke-width="1"/>
<ellipse cx="90" cy="45" rx="52" ry="22" fill="none" stroke="rgba(255,255,255,0.35)" stroke-width="1"/>
<ellipse cx="90" cy="45" rx="32" ry="13" fill="none" stroke="rgba(255,255,255,0.2)" stroke-width="1"/>
<circle cx="90" cy="45" r="4" fill="#F59E0B"/>
<circle cx="90" cy="13" r="3" fill="#10B981"/>
<circle cx="90" cy="32" r="3" fill="#3B82F6"/>
<circle cx="162" cy="44" r="3" fill="#8B5CF6"/>
</svg>`,
check: `<svg viewBox="0 0 180 90" xmlns="http://www.w3.org/2000/svg">
<ellipse cx="90" cy="45" rx="70" ry="28" fill="none" stroke="rgba(255,255,255,0.4)" stroke-width="1"/>
<ellipse cx="90" cy="45" rx="70" ry="28" fill="none" stroke="rgba(255,255,255,0.2)" stroke-width="1" transform="rotate(40 90 45)"/>
<ellipse cx="90" cy="45" rx="70" ry="28" fill="none" stroke="rgba(255,255,255,0.15)" stroke-width="1" transform="rotate(80 90 45)"/>
<ellipse cx="90" cy="45" rx="70" ry="28" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="1" transform="rotate(120 90 45)"/>
<circle cx="90" cy="45" r="4" fill="#F59E0B"/>
<circle cx="160" cy="45" r="3" fill="#EF4444"/>
<circle cx="45" cy="25" r="2.5" fill="#10B981"/>
<circle cx="130" cy="20" r="2.5" fill="#3B82F6"/>
<circle cx="60" cy="68" r="2.5" fill="#8B5CF6"/>
</svg>`,
threshold: `<svg viewBox="0 0 180 90" xmlns="http://www.w3.org/2000/svg">
<line x1="15" y1="25" x2="165" y2="25" stroke="#10B981" stroke-width="1.5" stroke-dasharray="4 3"/>
<line x1="15" y1="65" x2="165" y2="65" stroke="#EF4444" stroke-width="1.5" stroke-dasharray="4 3"/>
<rect x="15" y="25" width="150" height="40" fill="rgba(16,185,129,0.07)"/>
<ellipse cx="90" cy="45" rx="60" ry="18" fill="none" stroke="rgba(255,255,255,0.5)" stroke-width="1"/>
<circle cx="90" cy="45" r="4" fill="#F59E0B"/>
<circle cx="148" cy="42" r="3.5" fill="#F59E0B"/>
<text x="170" y="29" fill="#10B981" font-size="8" font-family="monospace">MAX</text>
<text x="170" y="69" fill="#EF4444" font-size="8" font-family="monospace">MIN</text>
</svg>`,
interval: `<svg viewBox="0 0 180 90" xmlns="http://www.w3.org/2000/svg">
<ellipse cx="70" cy="45" rx="52" ry="26" fill="none" stroke="rgba(255,255,255,0.5)" stroke-width="1"/>
<ellipse cx="115" cy="45" rx="52" ry="26" fill="none" stroke="rgba(139,92,246,0.6)" stroke-width="1" stroke-dasharray="5 3"/>
<circle cx="20" cy="43" r="3.5" fill="#10B981"/>
<circle cx="122" cy="19" r="3.5" fill="#8B5CF6"/>
<line x1="90" y1="15" x2="90" y2="75" stroke="rgba(255,255,255,0.2)" stroke-width="1" stroke-dasharray="3 2"/>
<text x="52" y="82" fill="rgba(255,255,255,0.5)" font-size="8" font-family="monospace">TODAY</text>
<text x="92" y="82" fill="rgba(139,92,246,0.8)" font-size="8" font-family="monospace">-7d</text>
</svg>`,
table: `<svg viewBox="0 0 180 90" xmlns="http://www.w3.org/2000/svg">
<line x1="30" y1="20" x2="30" y2="70" stroke="rgba(255,255,255,0.25)" stroke-width="1"/>
<line x1="90" y1="20" x2="90" y2="70" stroke="rgba(255,255,255,0.25)" stroke-width="1"/>
<line x1="150" y1="20" x2="150" y2="70" stroke="rgba(255,255,255,0.25)" stroke-width="1"/>
<line x1="20" y1="32" x2="160" y2="32" stroke="rgba(255,255,255,0.25)" stroke-width="1"/>
<line x1="20" y1="45" x2="160" y2="45" stroke="rgba(255,255,255,0.25)" stroke-width="1"/>
<line x1="20" y1="58" x2="160" y2="58" stroke="rgba(255,255,255,0.25)" stroke-width="1"/>
<ellipse cx="90" cy="45" rx="72" ry="32" fill="none" stroke="rgba(255,255,255,0.4)" stroke-width="1.5"/>
<circle cx="90" cy="45" r="4" fill="#F59E0B"/>
<circle cx="30" cy="32" r="2.5" fill="#10B981"/>
<circle cx="150" cy="58" r="2.5" fill="#8B5CF6"/>
</svg>`,
};
// ─── Card definitions ────────────────────────────────────────────────────────
const CARDS = [
{
id: 'value',
name: 'SQLValueCheckOperator',
image: 'images/SQLValueCheckOperator.webp',
tagline: 'One query. One expected value.',
range: 3, signal: 9, setup: 10,
code: `sql="SELECT COUNT(*) FROM planets",\npass_value=3`,
countersLabel: 'Best against: fixed reference tables',
useCount: 0,
},
{
id: 'column',
name: 'SQLColumnCheckOperator',
image: 'images/SQLColumnCheckOperator.webp',
tagline: 'Null, unique, min/max. One task.',
range: 7, signal: 9, setup: 7,
code: `"booking_id": {\n "null_check": {"equal_to": 0},\n "unique_check": {"equal_to": 0}\n}`,
countersLabel: 'Best against: structural field failures',
useCount: 0,
},
{
id: 'check',
name: 'SQLCheckOperator',
image: 'images/SQLCheckOperator.webp',
tagline: 'Any SQL. If it\'s falsy, it fails.',
range: 10, signal: 5, setup: 2,
code: `sql="""\n SELECT COUNT(*) = 0\n FROM payments p\n LEFT JOIN bookings b\n ON p.booking_id = b.booking_id\n WHERE b.booking_id IS NULL\n"""`,
countersLabel: 'Flexible: handles cross-table logic',
useCount: 0,
},
{
id: 'threshold',
name: 'SQLThresholdCheckOperator',
image: 'images/SQLThresholdCheckOperator.webp',
tagline: 'Value outside bounds? Check fails.',
range: 4, signal: 8, setup: 9,
code: `sql="SELECT AVG(amount_usd) FROM payments",\nmin_threshold=4000,\nmax_threshold=200000`,
countersLabel: 'Best against: impossible numeric values',
useCount: 0,
},
{
id: 'interval',
name: 'SQLIntervalCheckOperator',
image: 'images/SQLIntervalCheckOperator.webp',
tagline: 'Ratio check: today vs. N days ago.',
range: 4, signal: 7, setup: 5,
code: `days_back=-7,\nratio_formula="max_over_min",\nmetrics_thresholds={"SUM(...)": 3},\nignore_zero=False`,
countersLabel: 'Best against: temporal drift and anomalies',
useCount: 0,
},
{
id: 'table',
name: 'SQLTableCheckOperator',
image: 'images/SQLTableCheckOperator.webp',
tagline: 'Named business rules in plain SQL.',
range: 8, signal: 9, setup: 6,
code: `"net_fare_not_negative": {\n "check_statement":\n "total_net_fare_usd >= 0"\n}`,
countersLabel: 'Best against: business rule violations',
useCount: 0,
},
];
// ─── Attack definitions ──────────────────────────────────────────────────────
const ATTACKS = [
{
id: 'value-attack',
name: 'Reference Corruption',
monsterSays: '"I added 44 fake planets to your reference table. You now have 47 planets. Every fare calculation is broken."',
hint: 'The routes table must have an exact count. One extra row breaks everything downstream.',
wrongHint: 'Think: which operator checks for an exact expected value?',
bestCard: 'value',
why: 'SQLValueCheckOperator: checks if SELECT COUNT(*) matches exactly 3. Any deviation fails the task immediately.',
altCard: 'check',
altWhy: 'SQLCheckOperator can do this too, but you have to write the boolean assertion logic yourself.',
},
{
id: 'column-attack',
name: 'Structural Breakdown',
monsterSays: '"Null booking IDs everywhere. Duplicates in every column. Your primary key constraints are decorative now."',
hint: 'Field-level failure: nulls, uniqueness, and value ranges in a single table.',
wrongHint: 'Think: which card handles multiple column constraints in one task?',
bestCard: 'column',
why: 'SQLColumnCheckOperator: bundles null_check, unique_check, and min/max into one task. It tells you exactly which column failed.',
altCard: 'check',
altWhy: 'SQLCheckOperator works, but you would need a separate query for every single constraint.',
},
{
id: 'check-attack',
name: 'Referential Integrity Failure',
monsterSays: '"Payments referencing bookings that don\'t exist. Orphaned records, drifting through your database with nowhere to go."',
hint: 'Checking relationships between tables usually needs a JOIN.',
wrongHint: 'Think: which operator is the "Swiss Army Knife" for custom SQL and joins?',
bestCard: 'check',
why: 'SQLCheckOperator: the best choice for cross-table joins. If the query returns any rows (orphans), the check fails.',
altCard: 'table',
altWhy: 'SQLTableCheckOperator supports custom SQL but it is designed for single-table rules, not complex joins.',
},
{
id: 'threshold-attack',
name: 'Impossible Values',
monsterSays: '"Average payment: two cents. A Moon booking for $0.02. I corrupted your amounts and they still passed type validation."',
hint: 'The SQL is valid, but the values are garbage. Too low, or way too high.',
wrongHint: 'Think: which card checks if a value falls within a specific min/max range?',
bestCard: 'threshold',
why: 'SQLThresholdCheckOperator: great for keeping numbers in a plausible range. You just define the min and max bounds.',
altCard: 'check',
altWhy: 'SQLCheckOperator handles this if you write the BETWEEN logic manually in SQL.',
},
{
id: 'interval-attack',
name: 'Temporal Drift',
monsterSays: '"Revenue is down 400% compared to last week. Either your pipeline broke, or interplanetary travel became free."',
hint: 'Today\'s numbers look fine, but they are weird compared to last week.',
wrongHint: 'Think: which card compares today\'s metrics against historical data?',
bestCard: 'interval',
why: 'SQLIntervalCheckOperator: automatically handles the date math to compare today vs 7 days ago. Perfect for spotting drift.',
altCard: 'check',
altWhy: 'SQLCheckOperator could do it, but you would have to write all that annoying date-offset logic yourself.',
},
{
id: 'table-attack',
name: 'Business Rule Violation',
monsterSays: '"Net fares are negative. Discounts exceed gross fares. The laws of arithmetic no longer apply to your daily report."',
hint: 'This needs logic that only your team understands. Simple schema checks won\'t catch this.',
wrongHint: 'Think: which operator runs named business rules against a table?',
bestCard: 'table',
why: 'SQLTableCheckOperator: lets you name each business rule. When it fails, you know exactly which rule was broken.',
altCard: 'check',
altWhy: 'SQLCheckOperator can run these expressions, but failure messages won\'t be as clear as the named table checks.',
},
];
// ─── Utility ─────────────────────────────────────────────────────────────────
function shuffle(arr) {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
function getCard(id) { return CARDS.find(c => c.id === id); }
function isMobileLayout() { return window.innerWidth <= 700; }
// True touch/mobile detection using CSS media query — reliable on M-series Macs too
// pointer:coarse = finger/stylus. pointer:fine = mouse. Doesn't change on resize.
function isTouchPrimary() {
return window.matchMedia('(pointer: coarse)').matches;
}
function showScreen(id) {
document.querySelectorAll('.screen').forEach(s => {
s.classList.remove('active');
});
const target = document.getElementById(id);
if (target) target.classList.add('active');
}
// Haptic feedback (mobile only, silent on desktop)
function haptic(pattern) {
if ('vibrate' in navigator) {
try { navigator.vibrate(pattern); } catch (_) {}
}
}
function flashCritical() {
const el = document.createElement('div');
el.className = 'critical-flash';
document.body.appendChild(el);
setTimeout(() => el.remove(), 600);
}
function showFloatingText(text, x, y, isCritical = false) {
const div = document.createElement('div');
div.className = `floating-text ${isCritical ? 'critical' : ''}`;
div.textContent = text;
div.style.left = `${x}px`;
div.style.top = `${y}px`;
document.body.appendChild(div);
setTimeout(() => div.remove(), 800);
}
function shakeScreen() {
document.body.classList.add('shake-screen');
setTimeout(() => document.body.classList.remove('shake-screen'), 400);
}
function el(id) { return document.getElementById(id); }
// ─── Game state ───────────────────────────────────────────────────────────────
let state = {
attackOrder: [],
round: 0,
score: 0,
hp: 6,
roundTriedCards: [], // card IDs tried this round that were wrong
roundResolved: false, // whether the current round has been resolved (correct/alt played)
roundLog: [],
};
// ─── Init ─────────────────────────────────────────────────────────────────────
function init() {
el('btn-open-booster').addEventListener('click', showBooster);
el('btn-start-game').addEventListener('click', startGame);
el('btn-next').addEventListener('click', nextAttack);
el('css-pack-container').addEventListener('click', openBooster);
el('btn-twist').addEventListener('click', showTwist);
el('btn-observe').addEventListener('click', showObserveFight);
el('btn-deploy').addEventListener('click', deployObserve);
el('btn-true-restart').addEventListener('click', restart);
}
// ─── Responsive helpers ───────────────────────────────────────────────────────
function updateBoosterHint() {
const hint = el('booster-hint');
if (!hint || hint.textContent === '') return; // already opened
hint.textContent = isMobileLayout() ? 'Tap the pack to open' : 'Click the pack to open';
}
function updateRevealSub() {
const desktop = document.querySelector('.reveal-sub-desktop');
const mobile = document.querySelector('.reveal-sub-mobile');
if (!desktop || !mobile) return;
const isMob = isMobileLayout();
desktop.style.display = isMob ? 'none' : '';
mobile.style.display = isMob ? '' : 'none';
}
// ─── Intro → Booster ─────────────────────────────────────────────────────────
function showBooster() {
showScreen('screen-booster');
updateBoosterHint();
}
function openBooster() {
const container = el('css-pack-container');
if (container.classList.contains('opened')) return;
// Step 1: jiggle the pack
el('css-pack').classList.add('jiggle');
el('booster-hint').textContent = '';
setTimeout(() => {
// Step 2: pack tears : CSS transition fires on both halves
container.classList.add('opened');
// Step 3: flash at tear line
setTimeout(() => el('pack-flash').classList.add('active'), 80);
// Step 4: fade out the booster-wrap while halves are flying
setTimeout(() => {
el('booster-wrap').classList.add('fading');
// Step 5: once faded, hide it and cross-fade in the clean card grid
setTimeout(() => {
el('booster-wrap').style.display = 'none';
showReveal();
}, 420);
}, 550);
}, 340);
}
function showReveal() {
const revealWrap = el('reveal-wrap');
revealWrap.classList.add('visible');
updateRevealSub();
const container = el('reveal-cards');
container.innerHTML = '';
CARDS.forEach((card, i) => {
const div = document.createElement('div');
div.className = 'reveal-card';
div.style.animationDelay = `${i * 0.09}s`;
div.innerHTML = `<img src="${card.image}" alt="${card.name}">`;
div.addEventListener('mouseenter', () => {
if (!isTouchPrimary()) showCardPreview(card);
});
div.addEventListener('mouseleave', () => {
if (!isTouchPrimary()) hideCardPreview();
});
// Tap to show preview on mobile
div.addEventListener('click', () => {
if (isTouchPrimary() && isMobileLayout()) {
document.querySelectorAll('.reveal-card').forEach(c => c.classList.remove('selected'));
div.classList.add('selected');
showCardPreview(card, { modal: true });
} else if (!isTouchPrimary()) {
showCardPreview(card);
}
});
container.appendChild(div);
});
}
// ─── Start game ───────────────────────────────────────────────────────────────
function startGame() {
state = {
attackOrder: shuffle(ATTACKS),
round: 0,
score: 0,
hp: 6,
roundTriedCards: [],
roundResolved: false,
roundLog: [],
};
CARDS.forEach(c => {
c.useCount = 0;
});
hideCardPreview();
showScreen('screen-game');
renderHP();
renderHand();
renderAttack();
}
// ─── Render HP ────────────────────────────────────────────────────────────────
function renderHP() {
const container = el('monster-hp');
container.innerHTML = '';
for (let i = 0; i < 6; i++) {
const span = document.createElement('span');
span.className = `heart ${i < state.hp ? 'full' : 'empty'}`;
span.textContent = '♥\uFE0E';
span.dataset.idx = i;
container.appendChild(span);
}
}
// ─── Render current attack ────────────────────────────────────────────────────
function renderAttack() {
// Clear any lingering selection/preview from previous round
document.querySelectorAll('.hand-card').forEach(c => c.classList.remove('selected'));
hideCardPreview();
const attack = state.attackOrder[state.round];
el('round-num').textContent = state.round + 1;
el('attack-name').textContent = attack.name;
el('monster-speech').textContent = attack.monsterSays;
el('hint-text').textContent = attack.hint;
const attackBox = el('attack-box');
attackBox.style.display = 'block';
attackBox.classList.remove('glitch-in');
void attackBox.offsetWidth; // trigger reflow
attackBox.classList.add('glitch-in');
el('wrong-hint-box').classList.remove('visible');
el('result-box').classList.remove('visible');
state.roundTriedCards = [];
state.roundResolved = false;
updateScoreDisplay();
renderHand();
updateHandLabel();
}
// ─── Render hand ─────────────────────────────────────────────────────────────
function renderHand() {
const container = el('hand-cards');
container.innerHTML = '';
CARDS.forEach(card => {
const isTried = state.roundTriedCards.includes(card.id);
const isPlayable = !isTried && !state.roundResolved;
const div = document.createElement('div');
div.className = [
'hand-card',
isTried ? 'tried' : '',
!isPlayable && !isTried ? 'disabled' : '',
].filter(Boolean).join(' ');
div.dataset.id = card.id;
let labelHtml = '';
if (card.useCount > 0) {
labelHtml = `<div class="card-use-counter">USES: ${card.useCount}</div>`;
}
if (isTried) {
labelHtml += '<div class="card-state-label miss">✗\uFE0E</div>';
}
div.innerHTML = `<img src="${card.image}" alt="${card.name}">${labelHtml}`;
// Hover → show CSS card preview
div.addEventListener('mouseenter', () => {
if (!isTouchPrimary()) showCardPreview(card);
});
div.addEventListener('mouseleave', () => {
if (!isTouchPrimary()) hideCardPreview();
});
// Click / touch → play card (only if playable)
if (isPlayable) {
// touchstart: record position so we can skip drags in touchend
let _ts = { x: 0, y: 0 };
div.addEventListener('touchstart', e => {
_ts = { x: e.touches[0].clientX, y: e.touches[0].clientY };
}, { passive: true });
// touchend: direct handler bypasses iOS scroll-container click suppression.
// preventDefault() stops the synthetic click from double-firing.
div.addEventListener('touchend', e => {
e.preventDefault();
const t = e.changedTouches[0];
if (Math.abs(t.clientX - _ts.x) > 8 || Math.abs(t.clientY - _ts.y) > 8) return;
playCard(card.id, div, { clientX: t.clientX, clientY: t.clientY });
}, { passive: false });
// click: mouse / desktop fallback (touchend preventDefault stops double-fire on touch)
div.addEventListener('click', e => playCard(card.id, div, e));
}
container.appendChild(div);
});
}
function updateHandLabel() {
const tried = state.roundTriedCards.length;
const mobile = isMobileLayout();
if (tried === 0) {
el('hand-label').textContent = mobile
? 'TAP A CARD TO INSPECT AND PLAY'
: 'YOUR HAND : hover to inspect, click to play';
} else if (tried <= 2) {
el('hand-label').textContent = `${tried} wrong so far. Keep looking.`;
} else {
el('hand-label').textContent = 'Getting closer. Think about the type of failure.';
}
}
// ─── CSS Card Preview ─────────────────────────────────────────────────────────
// Card currently shown in preview (used by the mobile PLAY button)
let _previewCardId = null;
function showCardPreview(card, { playable = false, modal = false } = {}) {
if (!card) return;
_previewCardId = card.id;
const preview = el('card-preview');
el('cp-name').textContent = card.name;
el('cp-art').innerHTML = CARD_ART[card.id] || '';
el('cp-tagline').textContent = (card.tagline || '').toUpperCase();
el('cp-code').textContent = card.code || '';
el('cp-counters').textContent = card.countersLabel || '';
// Stat bars
const statsEl = el('cp-stats');
if (statsEl) {
statsEl.innerHTML = ['range', 'signal', 'setup'].map(stat => {
const val = card[stat] || 0;
const pct = (val / 10) * 100;
return `<div class="cp-stat">
<span class="cp-stat-label">${stat.toUpperCase()}</span>
<div class="cp-stat-bar"><div class="cp-stat-fill" style="width:${pct}%"></div></div>
<span class="cp-stat-num">${val}</span>
</div>`;
}).join('');
}
// Mobile bottom-sheet: add PLAY button + backdrop
const existingBtn = preview.querySelector('.cp-play-btn');
const existingHint = preview.querySelector('.cp-cancel-hint');
if (existingBtn) existingBtn.remove();
if (existingHint) existingHint.remove();
if (isMobileLayout() && modal) {
if (playable) {
const playBtn = document.createElement('button');
playBtn.className = 'cp-play-btn';
playBtn.textContent = '▶\uFE0E PLAY THIS CARD';
playBtn.addEventListener('click', () => {
const handCard = document.querySelector(`.hand-card[data-id="${card.id}"]`);
if (handCard) {
// Simulate a play — bypass selection check since user explicitly tapped PLAY
hideCardPreview();
playCardById(card.id, handCard, { clientX: window.innerWidth / 2, clientY: window.innerHeight / 2 });
}
});
preview.appendChild(playBtn);
}
const hint = document.createElement('span');
hint.className = 'cp-cancel-hint';
hint.textContent = 'tap backdrop to close';
hint.addEventListener('click', () => {
hideCardPreview();
if (el('screen-game')?.classList.contains('active')) updateHandLabel();
});
preview.appendChild(hint);
// Backdrop
showBackdrop();
}
preview.classList.add('visible');
preview.style.display = 'block';
}
function hideCardPreview() {
_previewCardId = null;
const preview = el('card-preview');
preview.classList.remove('visible');
preview.style.display = 'none';
// Remove any injected play button / cancel hint
preview.querySelectorAll('.cp-play-btn, .cp-cancel-hint').forEach(e => e.remove());
hideBackdrop();
}
function showBackdrop() {
if (document.querySelector('.preview-backdrop')) return;
const bd = document.createElement('div');
bd.className = 'preview-backdrop';
bd.addEventListener('click', () => {
hideCardPreview();
document.querySelectorAll('.hand-card, .reveal-card').forEach(c => c.classList.remove('selected'));
if (el('screen-game')?.classList.contains('active')) updateHandLabel();
});
document.body.appendChild(bd);
}
function hideBackdrop() {
document.querySelector('.preview-backdrop')?.remove();
}
// ─── Play a card ──────────────────────────────────────────────────────────────
// playCardById: the actual play logic (called from PLAY button on mobile, or direct click on desktop)
function playCardById(cardId, cardEl, event) {
if (state.roundResolved) return;
const card = getCard(cardId);
const attack = state.attackOrder[state.round];
const isPerfect = cardId === attack.bestCard;
const isAlt = cardId === attack.altCard;
// Deselect all and hide preview before playing
document.querySelectorAll('.hand-card').forEach(c => c.classList.remove('selected'));
hideCardPreview();
if (!isPerfect && !isAlt) {
// Wrong card : preview already hidden above; show hint and mark as tried
state.roundTriedCards.push(cardId);
cardEl.classList.add('tried');
cardEl.querySelector('img').classList.add('shaking');
setTimeout(() => cardEl.querySelector('img')?.classList.remove('shaking'), 400);
// Show floating MISS
showFloatingText('MISS', event.clientX, event.clientY);
haptic([30, 30, 30]); // rapid triple buzz for miss
// Show wrong-card hint
const triedCount = state.roundTriedCards.length;
let hintMsg = attack.wrongHint;
if (triedCount >= 3) {
const bestCard = getCard(attack.bestCard);
hintMsg = `Hint: look for the operator that handles "${bestCard.countersLabel.replace('Best against: ', '')}".`;
}
const wrongBox = el('wrong-hint-box');
el('wrong-hint-text').textContent = hintMsg;
wrongBox.classList.add('visible');
wrongBox.classList.add('shake');
setTimeout(() => wrongBox.classList.remove('shake'), 400);
renderHand();
updateHandLabel();
return; // don't advance round
}
// Correct or alt card : resolve round
state.roundResolved = true;
card.useCount++;
state.hp = Math.max(0, state.hp - 1);
if (isPerfect) {
state.score++;
setTimeout(flashCritical, 200);
showFloatingText('CRITICAL!', event.clientX, event.clientY, true);
shakeScreen();
haptic([80, 40, 120]); // strong double-pulse for critical
} else {
showFloatingText('OK!', event.clientX, event.clientY);
haptic(50); // single short buzz for OK
}
// Animate card played
cardEl.classList.add('playing');
state.roundLog.push({
attackName: attack.name,
cardId,
isPerfect,
isAlt,
triedCount: state.roundTriedCards.length,
});
setTimeout(() => {
renderHP();
animateMonster(isPerfect);
showResult(isPerfect, isAlt, card, attack);
updateScoreDisplay();
renderHand();
updateHandLabel();
}, 320);
}
// playCard: entry point from hand card click listener
// Desktop → play immediately on click
// Mobile → first tap shows bottom-sheet preview + PLAY button; PLAY button calls playCardById
function playCard(cardId, cardEl, event) {
if (state.roundResolved) return;
if (isTouchPrimary() && isMobileLayout()) {
// Mobile: tap shows card details in a bottom sheet with a PLAY button.
// If this same card is already selected (sheet already open), play it directly.
const isSelected = cardEl.classList.contains('selected');
if (!isSelected) {
// Deselect others, select this card, show preview sheet
document.querySelectorAll('.hand-card').forEach(c => c.classList.remove('selected'));
cardEl.classList.add('selected');
showCardPreview(getCard(cardId), { playable: true, modal: true });
haptic(30);
el('hand-label').textContent = 'TAP ▶\uFE0E PLAY TO USE THIS CARD';
return;
}
// Second tap on the already-selected card → play it (fallthrough)
hideCardPreview();
}
playCardById(cardId, cardEl, event);
}
// ─── Monster animation ────────────────────────────────────────────────────────
function animateMonster(isPerfect, monsterEl = el('game-monster')) {
if (!monsterEl) return;
monsterEl.classList.remove('hit', 'hit-critical');
void monsterEl.offsetWidth;
monsterEl.classList.add(isPerfect ? 'hit-critical' : 'hit');
setTimeout(() => monsterEl.classList.remove('hit', 'hit-critical'), 700);
// If normal game, heart loses its fill
if (monsterEl.id === 'game-monster') {
const hearts = document.querySelectorAll('#monster-hp .heart');
const lostHeart = hearts[state.hp];
if (lostHeart) {
lostHeart.classList.add('lost');
setTimeout(() => lostHeart.classList.remove('lost'), 400);
}
}
}
// ─── Show result ──────────────────────────────────────────────────────────────
function showResult(isPerfect, isAlt, card, attack) {
const badge = el('result-badge');
const cardNameEl = el('result-card-name');
const textEl = el('result-text');
const whyEl = el('result-why');
const resultBox = el('result-box');
el('attack-box').style.display = 'none';
el('wrong-hint-box').classList.remove('visible');
cardNameEl.textContent = card.name;
if (isPerfect) {
badge.textContent = '⚡\uFE0E CRITICAL CHECK!';
badge.className = 'result-badge critical';
const prefix = state.roundLog.at(-1).triedCount > 0
? `Found it after ${state.roundLog.at(-1).triedCount} wrong attempt${state.roundLog.at(-1).triedCount > 1 ? 's' : ''}. `
: 'Perfect match on first try. ';
textEl.textContent = prefix + 'This is exactly the right operator for this attack.';
whyEl.textContent = attack.why;
} else {
badge.textContent = '✓\uFE0E Acceptable : not optimal';
badge.className = 'result-badge alt';
const bestCard = getCard(attack.bestCard);
textEl.textContent = `${card.name} can handle this, but ${bestCard.name} is the sharper tool here.`;
whyEl.textContent = attack.altWhy;
}
resultBox.classList.add('visible');
}
// ─── Next attack ──────────────────────────────────────────────────────────────
function nextAttack() {
state.round++;
if (state.round >= state.attackOrder.length) {
showWin();
} else {
renderAttack();
}
}
// ─── Score display ────────────────────────────────────────────────────────────
function updateScoreDisplay() {
const played = state.roundLog.length;
el('score-display').textContent = `${state.score} / ${played}`;
}
// ─── Win screen ───────────────────────────────────────────────────────────────
function showWin() {
showScreen('screen-win');
el('win-score-num').textContent = `${state.score} / 6`;
const messages = {
6: "Perfect game. You know these operators inside out. Your pipelines are bulletproof.",
5: "Five critical checks. Just one minor slip: your data is in great hands.",
4: "Solid deck-building. A few more runs and you will have this locked down.",
3: "Halfway there. The patterns are starting to click.",
2: "Two critical hits. Keep at it: these operators will be second nature soon.",
1: 'Only one? <a href="https://www.astronomer.io/docs/learn/data-quality" target="_blank" style="color: var(--purple-light); text-decoration: underline;">Read the guide</a> for the full breakdown and try again.',
0: 'Even the monster is surprised. <a href="https://www.astronomer.io/docs/learn/data-quality" target="_blank" style="color: var(--purple-light); text-decoration: underline;">Check the guide</a> and run it back!',
};
el('win-message').innerHTML = messages[state.score];
const recapEl = el('win-recap');
recapEl.innerHTML = '';
state.roundLog.forEach(entry => {
const card = getCard(entry.cardId);
const row = document.createElement('div');
row.className = `recap-row ${entry.isPerfect ? 'hit' : 'miss'}`;
const icon = entry.isPerfect ? '⚡\uFE0E' : entry.isAlt ? '✓\uFE0E' : '~';
const triedNote = entry.triedCount > 0 ? ` <span class="recap-tries">(${entry.triedCount} wrong first)</span>` : '';
row.innerHTML = `
<span class="recap-attack">${entry.attackName}</span>
<span class="recap-card">${card.name}${triedNote}</span>
<span class="recap-icon">${icon}</span>
`;
recapEl.appendChild(row);
});
}
// ─── Restart ──────────────────────────────────────────────────────────────────
function restart() {
// Reset CSS pack
el('css-pack-container').classList.remove('opened');
el('css-pack').classList.remove('jiggle');
el('pack-flash').classList.remove('active');
el('pack-cards-burst').innerHTML = '';
el('booster-hint').textContent = 'Click the pack to open';
hideCardPreview();
const bw = el('booster-wrap');
bw.classList.remove('fading');
bw.style.display = '';
el('reveal-wrap').classList.remove('visible');
showScreen('screen-intro');
}
// ─── PLOT TWIST: Airflow being eaten ─────────────────────────────────────────
const TERMINAL_LINES = [
{ text: '$ airflow scheduler status', delay: 200, cls: 'term-cmd' },
{ text: '> Connecting...', delay: 900, cls: 'term-info' },
{ text: '> ERROR: Scheduler not responding', delay: 1800, cls: 'term-error' },
{ text: '> Retrying... (1/3)', delay: 2600, cls: 'term-warn' },
{ text: '> Retrying... (2/3)', delay: 3200, cls: 'term-warn' },
{ text: '> SCHEDULER DOWN', delay: 3900, cls: 'term-error blink' },
{ text: '> WORKER UNREACHABLE', delay: 4500, cls: 'term-error' },
{ text: '> DQ Dag: task_runner : NOT RUNNING', delay: 5100, cls: 'term-error' },
{ text: '> Your SQL operators cannot reach the battlefield.', delay: 5900, cls: 'term-dim' },
];
function showTwist() {
showScreen('screen-twist');
el('twist-speech').style.opacity = '0';
el('twist-cta').style.opacity = '0';
el('twist-cta').style.pointerEvents = 'none';
// Monster slides in after a beat
setTimeout(() => {
el('twist-monster').classList.add('slide-in');
}, 500);
// Airflow logo glitches and gets eaten
setTimeout(() => {
el('airflow-logo').classList.add('glitching');
}, 3600);
setTimeout(() => {
el('airflow-logo').classList.add('eating');
el('twist-monster').classList.add('chomping');
}, 4200);
setTimeout(() => {
el('airflow-logo').classList.add('eaten');
el('twist-monster').classList.remove('chomping');
}, 5000);
// Terminal lines type in
const termBody = el('term-body');
termBody.innerHTML = '';
TERMINAL_LINES.forEach(({ text, delay, cls }) => {
setTimeout(() => {
const line = document.createElement('div');
line.className = `term-line ${cls}`;
line.textContent = text;
termBody.appendChild(line);
termBody.scrollTop = termBody.scrollHeight;
}, delay);
});
// Monster taunts
setTimeout(() => {
el('twist-bubble').textContent = '"Your operators can\'t run if I eat the scheduler."';
el('twist-speech').style.opacity = '1';
}, 6200);
// CTA appears
setTimeout(() => {
el('twist-cta').style.opacity = '1';
el('twist-cta').style.pointerEvents = '';
}, 7200);
}
// ─── OBSERVE BOSS FIGHT ───────────────────────────────────────────────────────
let obsHp = 3;
function showObserveFight() {
obsHp = 3;
showScreen('screen-observe');
renderObsHP();
el('monitor-log').classList.remove('visible');
el('btn-deploy').disabled = false;
el('btn-deploy').textContent = '★ DEPLOY OBSERVABILITY';
el('ml-body').innerHTML = '';
el('observe-card').classList.remove('deployed');
el('obs-intro-box').style.display = 'block';
}
function renderObsHP() {
el('obs-hp').textContent = Array.from({ length: 3 }, (_, i) => i < obsHp ? '♥\uFE0E' : '♡\uFE0E').join(' ');
}
const MONITOR_ALERTS = [
{
label: 'ROW VOLUME CHANGE',
msg: 'daily_planet_report: row count dropped 94% vs. last run.',
delay: 0,
severity: 'critical',
},
{
label: 'NULL PERCENTAGE',
msg: 'bookings.booking_id: null rate is 38%. Expected 0%.',
delay: 900,
severity: 'critical',
},
{
label: 'SCHEMA DRIFT',
msg: 'payments.amount_usd: column type changed from FLOAT to VARCHAR.',
delay: 1800,
severity: 'critical',
},
{
label: 'LINEAGE IMPACT',
msg: 'daily_planet_report affected. 3 downstream assets are now at risk.',
delay: 2600,
severity: 'info',
},
{
label: 'CUSTOM SQL MONITOR',
msg: 'check_avg_payment: AVG(amount_usd) is $0.02. Way below threshold.',
delay: 3300,
severity: 'critical',
},
];
function deployObserve() {
el('btn-deploy').disabled = true;
el('btn-deploy').textContent = 'MONITORING ACTIVE...';
el('observe-card').classList.add('deployed');
el('obs-intro-box').style.display = 'none';
const logEl = el('monitor-log');
logEl.classList.add('visible');
const body = el('ml-body');
body.innerHTML = '';
let hitsLanded = 0;
MONITOR_ALERTS.forEach(({ label, msg, delay, severity }) => {
setTimeout(() => {
// Add alert to log
const row = document.createElement('div');
row.className = `ml-row ml-${severity}`;
row.innerHTML = `<span class="ml-label">${label}</span><span class="ml-msg">${msg}</span>`;
body.appendChild(row);
body.scrollTop = body.scrollHeight;
// Hit monster every 2 alerts (at indices 0, 2, 4)
if (hitsLanded < 3 && severity === 'critical') {
const monster = el('obs-monster');
animateMonster(true, monster);
obsHp = Math.max(0, obsHp - 1);
hitsLanded++;
renderObsHP();