-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolitaire.js
More file actions
1779 lines (1533 loc) · 53.7 KB
/
Copy pathsolitaire.js
File metadata and controls
1779 lines (1533 loc) · 53.7 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
/*
* Copyright 2026 Akop Karapetyan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// --- Constants ---
const SC_VEGAS = 'vegas';
const SC_STANDARD = 'standard';
const SC_NONE = 'none';
const SC_ALL = [SC_STANDARD, SC_VEGAS, SC_NONE];
const LOGICAL_W = 640; // logical canvas width (fixed; canvas scales to match)
const CARD_W = 71; // sprite tile width (px)
const CARD_H = 96; // sprite tile height (px)
const IX_EMPTY_SLOT = 77; // sprite index of the empty card slot
const IX_WASTE_RECY = 75; // sprite index of the recyclable waste slot
const IX_WASTE_DONE = 76; // sprite index of the finished waste slot
const DECKS = [ // available decks
{ start: 0, frames: [52] }, // diag hatch
{ start: 0, frames: [53] }, // horiz hatch
{ start: 0, frames: [54] }, // fish, light blue
{ start: 0, frames: [55] }, // fish, dark blue
{ start: 0, frames: [56] }, // plants, black
{ start: 0, frames: [57] }, // plants, blue
{ start: 0, frames: [60,59,58,59] }, // robot
{ start: 0, frames: [61] }, // rose
{ start: 0, frames: [62] }, // cone
{ start: 0, frames: [63,64] }, // castle
{ start: 50, frames: [65,66,67,66] }, // sun & palm tree
{ start: 15, frames: [68,69,70,69] }, // hand holding cards
];
const SS_CARDS_PER_ROW = 13; // cards per row in the sprite sheet
const DC_CARDS_PER_ROW = 6; // deck chooser cards per row
const DC_CARD_PADDING = 4; // deck chooser card padding
const TIMER_INTERVAL = 250; // timer interval (ms)
const SPRITE_URL = 'cards.png';
// Suit → sprite row mapping
const SUIT_ROW = { S: 0, H: 1, C: 2, D: 3 };
const SUITS = ['S', 'H', 'C', 'D'];
const RED_SUITS = new Set(['H', 'D']);
// Base layout positions in logical coordinates (640 wide)
const L = {
STOCK_X: 17,
STOCK_Y: 5,
THICK_X_OFFSET: 2, // h. offset between cards added for thickness effect
THICK_Y_OFFSET: 1, // v. offset between cards added for thickness effect
WASTE_X: 105,
WASTE_Y: 5,
FOUND_X: [281, 369, 457, 545],
FOUND_Y: 5,
TAB_X: [17, 105, 193, 281, 369, 457, 545],
TAB_Y: 107,
FD_DY: 3, // face-down card vertical offset
FU_DY: 20, // face-up card offset (base; auto-compressed for tall piles)
WASTE3_DX: 14, // horizontal fan offset in Draw-3 mode
WASTE3_DY: 1, // vertical fan offset in Draw-3 mode
};
// Standard-scoring point deltas
const SCORE = {
WASTE_TO_FOUND: 10,
WASTE_TO_TAB: 5,
TAB_FLIP: 5,
FOUND_TO_TAB: -15,
RECYCLE: -100,
};
// --- Card Utilities ---
function makeCard(suit, rank) {
return { suit, rank, faceUp: false };
}
function cloneCard(c) {
return { suit: c.suit, rank: c.rank, faceUp: c.faceUp };
}
function cardIsRed(c) {
return RED_SUITS.has(c.suit);
}
function rankLabel(rank) {
const face = { 1: 'A', 11: 'J', 12: 'Q', 13: 'K' };
return face[rank] ?? String(rank);
}
function suitSymbol(suit) {
const syms = { S: '\u2660', H: '\u2665', C: '\u2663', D: '\u2666' };
return syms[suit];
}
// --- State ---
const canvas = document.getElementById('board');
const ctx = canvas.getContext('2d');
let spriteSheet = null;
let spriteReady = false; // true once the sprite image has loaded
let pendingBack = 9; // staged value while deck dialog is open
let deckFrame = 0; // current frame of the deck animation
const options = {
timed: true,
statusBar: true,
outlineDrag: false,
drawCount: 3,
scoring: SC_STANDARD,
deck: 9,
};
let state = null; // full game state object (see freshState)
let undoState = null; // one-level undo snapshot
let drag = null; // active drag descriptor or null
// Win animation
let winParticles = [];
let winAnimating = false;
let winAnimFrame = null;
let winAbortFn = null; // called to stop the win animation early
// Timer
let timerInterval = null;
let timerStart = 0;
let previouslyElapsed = -1;
// Double-tap detection (mobile)
let lastTapTime = 0;
let lastTapX = 0;
let lastTapY = 0;
let lastDoubleTapMs = 0;
// Active dropdown menu
let activeMenu = null;
// --- Deck & Deal ---
function freshState() {
return {
stock: [],
waste: [],
foundations: [[], [], [], []], // indexed 0-3, one per suit slot
tableau: [[], [], [], [], [], [], []],
drawCount: options.drawCount,
scoring: options.scoring,
score: options.scoring === SC_VEGAS ? -52 : 0,
elapsed: 0,
passes: 0,
won: false,
autoCompleting: false,
};
}
function makeDeck() {
const deck = [];
for (const suit of SUITS) {
for (let rank = 1; rank <= 13; rank++) {
deck.push(makeCard(suit, rank));
}
}
return deck;
}
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
function deal() {
const s = freshState();
const deck = makeDeck();
shuffle(deck);
// Deal tableau: column i gets i+1 cards, top card face-up
let di = 0;
for (let col = 0; col < 7; col++) {
for (let row = 0; row <= col; row++) {
const card = deck[di++];
card.faceUp = (row === col);
s.tableau[col].push(card);
}
}
// Remaining cards go to stock, face-down
while (di < deck.length) {
deck[di].faceUp = false;
s.stock.push(deck[di++]);
}
return s;
}
function deepClone(s) {
return {
stock: s.stock.map(cloneCard),
waste: s.waste.map(cloneCard),
foundations: s.foundations.map(f => f.map(cloneCard)),
tableau: s.tableau.map(col => col.map(cloneCard)),
drawCount: s.drawCount,
scoring: s.scoring,
score: s.score,
elapsed: s.elapsed,
passes: s.passes,
won: s.won,
autoCompleting: s.autoCompleting,
};
}
// --- Move Validation ---
function canDropOnTableau(card, colIdx) {
const col = state.tableau[colIdx];
if (col.length === 0) {
return card.rank === 13; // only Kings on empty
}
const top = col[col.length - 1];
return top.faceUp &&
cardIsRed(card) !== cardIsRed(top) &&
card.rank === top.rank - 1;
}
function canDropOnFoundation(card, fi) {
const found = state.foundations[fi];
if (found.length === 0) {
return card.rank === 1; // Ace starts
}
const top = found[found.length - 1];
return card.suit === top.suit && card.rank === top.rank + 1;
}
// Return the index of the best foundation that will accept card, or -1
function findBestFoundation(card) {
for (let i = 0; i < 4; i++) {
if (canDropOnFoundation(card, i)) {
return i;
}
}
return -1;
}
// --- Scoring ---
function addScore(event) {
if (state.scoring !== SC_STANDARD) {
return;
}
const delta = SCORE[event] ?? 0;
state.score = Math.max(0, state.score + delta);
updateStatusBar();
}
function addVegasScore(delta) {
if (state.scoring !== SC_VEGAS) {
return;
}
state.score += delta;
updateStatusBar();
}
function computeWinBonus() {
if (state.scoring === SC_STANDARD && options.timed && state.elapsed > 0) {
state.score += Math.floor(700000 / state.elapsed);
updateStatusBar();
}
}
// --- Layout Helpers ---
// Pixels-per-logical-pixel for the current canvas size
function getScale() {
const dpr = window.devicePixelRatio || 1;
return (canvas.width / dpr) / LOGICAL_W;
}
// Logical height of the canvas
function logicalH() {
const dpr = window.devicePixelRatio || 1;
return canvas.height / dpr / getScale();
}
// Compute the dynamic face-up reveal offset for a tableau column.
// Compresses the pile if it would otherwise overflow the canvas.
function faceUpDy(colIdx) {
const pile = state.tableau[colIdx];
const fdCount = pile.filter(c => !c.faceUp).length;
const fuCount = pile.filter(c => c.faceUp).length;
const avail = logicalH() - L.TAB_Y - CARD_H - 8;
let dy = L.FU_DY;
if (fuCount > 1 && fdCount * L.FD_DY + fuCount * dy > avail) {
dy = Math.max(10, Math.floor((avail - fdCount * L.FD_DY) / fuCount));
}
return dy;
}
// --- Rendering ---
function resizeCanvas() {
const dpr = window.devicePixelRatio || 1;
canvas.width = Math.round(canvas.clientWidth * dpr);
canvas.height = Math.round(canvas.clientHeight * dpr);
render();
}
function render() {
if (!state) {
return;
}
const dpr = window.devicePixelRatio || 1;
const scale = getScale();
const lh = logicalH();
ctx.save();
ctx.scale(scale * dpr, scale * dpr);
// Green felt background
ctx.fillStyle = '#008000';
ctx.fillRect(0, 0, LOGICAL_W, lh);
drawBoard(lh);
if (winParticles.length > 0) {
drawWinParticles();
} else if (state.won && !winAnimating) {
drawWinOverlay(lh);
}
if (drag) {
drawDragStack();
}
ctx.restore();
}
function drawBoard(lh) {
drawStock();
drawWaste();
drawFoundations();
drawTableau(lh);
}
function canRecycle() {
return state.scoring !== SC_VEGAS || state.passes < (state.drawCount - 1);
}
function drawStock(topCardOnly = false) {
if (state.stock.length > 0) {
const cardCount = Math.trunc((state.stock.length - 1) / 8) + 1;
for (let i = 0; i < cardCount; i++) {
if (!topCardOnly || i === cardCount - 1) {
drawBack(
L.STOCK_X + i * L.THICK_X_OFFSET,
L.STOCK_Y + i * L.THICK_Y_OFFSET,
(i == cardCount - 1) ? deckFrame : 0, // top card is animated
);
}
}
} else if (!topCardOnly) {
drawWasteSlot(L.STOCK_X, L.STOCK_Y, canRecycle());
}
}
function drawWaste() {
const wasteLen = state.waste.length;
const isDragged = drag && drag.src.type === 'waste';
if (wasteLen === 0) {
return;
}
// We draw some cards for thickness effect, depending on the number
// left in the waste. Doesn't really matter what we draw - it'll be covered
const effectCardCount = (state.drawCount === 1)
? Math.max(0, Math.trunc((wasteLen - 2) / 10))
: Math.max(0, Math.trunc((wasteLen - 3) / 10));
let offsetX = L.WASTE_X;
let offsetY = L.WASTE_Y;
for (let i = 0; i < effectCardCount; i++) {
drawCard(
state.waste[0],
offsetX,
offsetY
);
offsetX += L.THICK_X_OFFSET;
offsetY += L.THICK_Y_OFFSET;
}
if (state.drawCount === 1) {
if (!isDragged) {
drawCard(state.waste[wasteLen - 1], offsetX, offsetY);
}
return;
}
// Draw-3: fan of up to 3 cards; only top card is playable
const count = Math.min(3, wasteLen);
const start = wasteLen - count;
const topIdx = wasteLen - 1;
for (let i = 0; i < count; i++) {
const cardIdx = start + i;
if (isDragged && cardIdx === topIdx) {
continue;
}
drawCard(
state.waste[cardIdx],
offsetX,
offsetY
);
offsetX += L.WASTE3_DX;
offsetY += L.WASTE3_DY;
}
}
function drawFoundations() {
for (let fi = 0; fi < 4; fi++) {
const x = L.FOUND_X[fi];
const y = L.FOUND_Y;
const pile = state.foundations[fi];
const isDragged = drag && drag.src.type === 'foundation' && drag.src.fi === fi;
const visLen = pile.length - (isDragged ? 1 : 0);
if (visLen <= 0) {
drawSlot(x, y);
} else {
drawCard(pile[visLen - 1], x, y);
}
}
}
function drawTableau(lh) {
for (let col = 0; col < 7; col++) {
const pile = state.tableau[col];
const cx = L.TAB_X[col];
if (pile.length === 0) {
continue;
}
const isDragSrc = drag && drag.src.type === 'tableau' && drag.src.col === col;
const cutIdx = isDragSrc ? drag.src.idx : pile.length;
const dy = faceUpDy(col);
let y = L.TAB_Y;
for (let j = 0; j < cutIdx; j++) {
const card = pile[j];
card.faceUp ? drawCard(card, cx, y) : drawBack(cx, y);
if (j < cutIdx - 1) y += pile[j].faceUp ? dy : L.FD_DY;
}
}
}
// Draw a face-up card using the sprite sheet (or vector fallback)
function drawCard(card, x, y) {
if (spriteReady) {
const sx = (card.rank - 1) * CARD_W;
const sy = SUIT_ROW[card.suit] * CARD_H;
ctx.drawImage(spriteSheet, sx, sy, CARD_W, CARD_H, x, y, CARD_W, CARD_H);
} else {
drawCardFallback(card, x, y);
}
}
// Draw a face-down card back
function drawBack(x, y, frame = 0) {
if (spriteReady) {
const spriteIndex = DECKS[options.deck].frames[frame];
const sx = (spriteIndex * CARD_W) % spriteSheet.width;
const sy = Math.trunc(spriteIndex / SS_CARDS_PER_ROW) * CARD_H;
ctx.drawImage(spriteSheet, sx, sy, CARD_W, CARD_H, x, y, CARD_W, CARD_H);
} else {
drawBackFallback(x, y);
}
}
// Draw an empty card-slot outline; showArrow draws a recycle icon
function drawSlot(x, y) {
ctx.save();
if (spriteReady) {
const sx = (IX_EMPTY_SLOT * CARD_W) % spriteSheet.width;
const sy = Math.trunc(IX_EMPTY_SLOT / SS_CARDS_PER_ROW) * CARD_H;
ctx.drawImage(spriteSheet, sx, sy, CARD_W, CARD_H, x, y, CARD_W, CARD_H);
} else {
ctx.strokeStyle = '#004400';
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
roundRect(x, y, CARD_W, CARD_H, 4);
ctx.stroke();
ctx.setLineDash([]);
}
ctx.restore();
}
function drawWasteSlot(x, y, canRecycle) {
ctx.save();
if (spriteReady) {
const spriteIndex = canRecycle ? IX_WASTE_RECY : IX_WASTE_DONE;
const sx = (spriteIndex * CARD_W) % spriteSheet.width;
const sy = Math.trunc(spriteIndex / SS_CARDS_PER_ROW) * CARD_H;
ctx.drawImage(spriteSheet, sx, sy, CARD_W, CARD_H, x, y, CARD_W, CARD_H);
} else {
ctx.strokeStyle = '#004400';
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
roundRect(x, y, CARD_W, CARD_H, 4);
ctx.stroke();
ctx.setLineDash([]);
if (canRecycle) {
const cx = x + CARD_W / 2;
const cy = y + CARD_H / 2;
ctx.strokeStyle = '#006600';
ctx.lineWidth = 2;
// Circle arc
ctx.beginPath();
ctx.arc(cx, cy, 14, -Math.PI * 0.85, Math.PI * 0.85);
ctx.stroke();
// Arrow tip at the open end
const angle = Math.PI * 0.85;
const ax = cx + 14 * Math.cos(angle);
const ay = cy + 14 * Math.sin(angle);
ctx.beginPath();
ctx.moveTo(ax - 5, ay - 2);
ctx.lineTo(ax, ay + 4);
ctx.lineTo(ax + 5, ay - 2);
ctx.stroke();
}
}
ctx.restore();
}
// Vector fallback card face (used when sprite sheet has not yet loaded)
function drawCardFallback(card, x, y) {
const isRed = cardIsRed(card);
const color = isRed ? '#cc0000' : '#000000';
ctx.fillStyle = '#ffffff';
roundRect(x, y, CARD_W, CARD_H, 4);
ctx.fill();
ctx.strokeStyle = '#aaaaaa';
ctx.lineWidth = 1;
ctx.stroke();
const rl = rankLabel(card.rank);
const sym = suitSymbol(card.suit);
ctx.fillStyle = color;
ctx.font = 'bold 11px Arial';
ctx.textBaseline = 'top';
ctx.textAlign = 'left';
ctx.fillText(rl, x + 3, y + 2);
ctx.fillText(sym, x + 3, y + 15);
// Bottom-right corner (rotated 180°)
ctx.save();
ctx.translate(x + CARD_W - 3, y + CARD_H - 2);
ctx.rotate(Math.PI);
ctx.fillText(rl, 0, 0);
ctx.fillText(sym, 0, 13);
ctx.restore();
// Centre suit symbol
ctx.font = '26px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(sym, x + CARD_W / 2, y + CARD_H / 2);
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
}
// Vector fallback card back
function drawBackFallback(x, y) {
ctx.fillStyle = '#000080';
roundRect(x, y, CARD_W, CARD_H, 4);
ctx.fill();
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 2;
ctx.stroke();
// Simple vertical stripe pattern
ctx.strokeStyle = '#3333aa';
ctx.lineWidth = 1;
for (let i = 8; i < CARD_W - 4; i += 8) {
ctx.beginPath();
ctx.moveTo(x + i, y + 5);
ctx.lineTo(x + i, y + CARD_H - 5);
ctx.stroke();
}
}
// Draw the currently-dragged card stack at its current position
function drawDragStack() {
const cards = drag.cards;
if (options.outlineDrag && !drag.isTouch) {
ctx.strokeStyle = 'rgba(0,0,0,0.7)';
ctx.lineWidth = 2;
ctx.setLineDash([4, 4]);
for (let i = 0; i < cards.length; i++) {
roundRect(drag.x, drag.y + i * L.FU_DY, CARD_W, CARD_H, 4);
ctx.stroke();
}
ctx.setLineDash([]);
} else {
ctx.save();
if (drag.isTouch) {
// Subtle scale-up on touch for finger-clearance feedback
const sc = 1.06;
const ox = (CARD_W * (sc - 1)) / 2;
const oy = (CARD_H * (sc - 1)) / 2;
ctx.translate(drag.x - ox, drag.y - oy);
ctx.scale(sc, sc);
} else {
ctx.translate(drag.x, drag.y);
}
for (let i = 0; i < cards.length; i++) {
drawCard(cards[i], 0, i * L.FU_DY);
}
ctx.restore();
}
}
function drawWinParticles() {
for (const p of winParticles) {
drawCard(p.card, p.x, p.y);
}
}
// Full-screen win overlay shown after the animation finishes
function drawWinOverlay(lh) {
ctx.fillStyle = 'rgba(0,0,0,0.45)';
ctx.fillRect(0, 0, LOGICAL_W, lh);
const cx = LOGICAL_W / 2;
const cy = lh / 2;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#ffffff';
ctx.font = 'bold 30px Arial';
ctx.fillText('You Win!', cx, cy - 26);
if (state.scoring !== SC_NONE) {
const label = state.scoring === SC_VEGAS
? `$${state.score}`
: `Score: ${state.score}`;
ctx.font = '16px Arial';
ctx.fillText(label, cx, cy + 10);
}
ctx.fillStyle = '#cccccc';
ctx.font = '13px Arial';
ctx.fillText('Click or tap to deal again', cx, cy + 40);
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
}
// Helper: build a rounded-rect path (no stroke/fill; caller does that)
function roundRect(x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
// --- Drag & Drop ---
// Convert a DOM client position to logical (640-wide) canvas coordinates
function toLogical(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
const scl = LOGICAL_W / rect.width;
return {
x: (clientX - rect.left) * scl,
y: (clientY - rect.top) * scl,
};
}
// Return the y-positions of each card in a tableau column
function tabCardYs(colIdx) {
const pile = state.tableau[colIdx];
const dy = faceUpDy(colIdx);
const ys = [];
let y = L.TAB_Y;
for (let j = 0; j < pile.length; j++) {
ys.push(y);
if (j < pile.length - 1) y += pile[j].faceUp ? dy : L.FD_DY;
}
return ys;
}
// Hit-test a logical point; returns a descriptor or null
function hitTest(lx, ly) {
// Tableau columns (right-to-left so rightmost column takes priority)
for (let col = 6; col >= 0; col--) {
const pile = state.tableau[col];
if (pile.length === 0) continue;
const cx = L.TAB_X[col];
if (lx < cx || lx > cx + CARD_W) continue;
const ys = tabCardYs(col);
for (let j = pile.length - 1; j >= 0; j--) {
const top = ys[j];
const bottom = j < pile.length - 1 ? ys[j + 1] : top + CARD_H;
if (ly >= top && ly <= bottom) {
return { type: 'tableau', col, idx: j, cardX: cx, cardY: top };
}
}
}
// Waste pile top card
if (state.waste.length > 0) {
const count = state.drawCount === 3 ? Math.min(3, state.waste.length) : 1;
const topX = L.WASTE_X + (count - 1) * L.WASTE3_DX;
if (lx >= topX && lx <= topX + CARD_W &&
ly >= L.WASTE_Y && ly <= L.WASTE_Y + CARD_H) {
return { type: 'waste', cardX: topX, cardY: L.WASTE_Y };
}
}
// Foundation piles
for (let fi = 0; fi < 4; fi++) {
const fx = L.FOUND_X[fi];
if (lx >= fx && lx <= fx + CARD_W &&
ly >= L.FOUND_Y && ly <= L.FOUND_Y + CARD_H) {
return { type: 'foundation', fi, cardX: fx, cardY: L.FOUND_Y };
}
}
// Stock pile
if (lx >= L.STOCK_X && lx <= L.STOCK_X + CARD_W &&
ly >= L.STOCK_Y && ly <= L.STOCK_Y + CARD_H) {
return { type: 'stock' };
}
return null;
}
function onPointerDown(lx, ly, isTouch) {
// Clicking anywhere on the win overlay starts a new game
if (state.won && !winAnimating) {
startNewGame();
return;
}
if (state.won || state.autoCompleting || drag) {
return;
}
if (state && !timerInterval) {
startTimer();
}
const hit = hitTest(lx, ly);
if (!hit) {
return;
}
if (hit.type === 'stock') {
undoState = deepClone(state);
doDrawStock();
render();
return;
}
let cards = [];
let src = null;
if (hit.type === 'waste') {
const top = state.waste[state.waste.length - 1];
if (!top || !top.faceUp) return;
cards = [cloneCard(top)];
src = { type: 'waste' };
} else if (hit.type === 'tableau') {
const pile = state.tableau[hit.col];
const card = pile[hit.idx];
if (!card || !card.faceUp) return;
cards = pile.slice(hit.idx).map(cloneCard);
src = { type: 'tableau', col: hit.col, idx: hit.idx };
} else if (hit.type === 'foundation') {
const found = state.foundations[hit.fi];
if (found.length === 0) return;
cards = [cloneCard(found[found.length - 1])];
src = { type: 'foundation', fi: hit.fi };
} else {
return;
}
undoState = deepClone(state);
drag = {
cards,
src,
x: hit.cardX,
y: hit.cardY,
ox: lx - hit.cardX,
oy: ly - hit.cardY,
isTouch,
};
render();
}
function onPointerMove(lx, ly) {
if (!drag) return;
drag.x = lx - drag.ox;
drag.y = ly - drag.oy;
render();
}
function onPointerUp(lx, ly) {
if (!drag) return;
// Use the centre of the dragged card (not the raw pointer) for drop detection.
// This makes it much easier to place cards accurately.
const cx = drag.x + CARD_W / 2;
const cy = drag.y + CARD_H / 2;
const target = findDropTarget(cx, cy);
const moved = target ? commitMove(drag.src, drag.cards, target) : false;
if (!moved) undoState = null; // cancelled drag → discard undo snapshot
drag = null;
render();
if (moved) {
checkAutoComplete();
checkWin();
}
}
// Find a valid drop target for the current drag, or return null
function findDropTarget(lx, ly) {
// Tableau columns
for (let col = 0; col < 7; col++) {
const cx = L.TAB_X[col];
const pile = state.tableau[col];
// Target zone is the last visible card area (or the empty-column slot)
let targetY = L.TAB_Y;
if (pile.length > 0) {
const dy = faceUpDy(col);
for (let j = 0; j < pile.length - 1; j++) {
targetY += pile[j].faceUp ? dy : L.FD_DY;
}
}
// Generous hit zone: 16px slack above and below the target card
if (lx >= cx && lx <= cx + CARD_W &&
ly >= targetY - 16 && ly <= targetY + CARD_H + 8) {
if (drag.src.type === 'tableau' && drag.src.col === col) continue;
if (canDropOnTableau(drag.cards[0], col)) return { type: 'tableau', col };
}
}
// Foundation piles (single-card drops only)
if (drag.cards.length === 1) {
for (let fi = 0; fi < 4; fi++) {
const fx = L.FOUND_X[fi];
if (lx >= fx && lx <= fx + CARD_W &&
ly >= L.FOUND_Y - 8 && ly <= L.FOUND_Y + CARD_H + 8) {
if (canDropOnFoundation(drag.cards[0], fi)) return { type: 'foundation', fi };
}
}
}
return null;
}
// Apply a move to the game state and update scoring
function commitMove(src, cards, target) {
// Remove cards from source pile
if (src.type === 'waste') {
state.waste.pop();
} else if (src.type === 'tableau') {
state.tableau[src.col].splice(src.idx);
flipTopTableauCard(src.col);
} else if (src.type === 'foundation') {
state.foundations[src.fi].pop();
addScore('FOUND_TO_TAB');
}
// Place cards on target pile
if (target.type === 'tableau') {
for (const c of cards) {
c.faceUp = true;
state.tableau[target.col].push(c);
}
if (src.type === 'waste') addScore('WASTE_TO_TAB');
} else if (target.type === 'foundation') {
const c = cards[0];
c.faceUp = true;
state.foundations[target.fi].push(c);
if (src.type === 'waste') addScore('WASTE_TO_FOUND');
addVegasScore(5);
}
saveState();
return true;
}
function saveState() {
const s = serialize(state);
if (s) {
window.history.replaceState(null, '', `#${s}`);
} else {
window.history.replaceState(null, '', ' ');
}
}
function saveOptions(opts) {
const optString = JSON.stringify(opts);
const date = new Date();
date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000)); // 1 year
document.cookie = `options=${encodeURIComponent(optString)}; expires=${date.toUTCString()}; path=/; SameSite=Strict; Secure`;
}
function loadOptions() {
const optionsCookie = document.cookie.split('; ').find(row => row.startsWith('options='));
if (optionsCookie) {
const optString = decodeURIComponent(optionsCookie.split('=')[1]);
if (optString) {
return JSON.parse(optString);
}
}
return null;
}
// Turn over the top face-down card in a tableau column after cards are removed
function flipTopTableauCard(col) {
const pile = state.tableau[col];
if (pile.length > 0 && !pile[pile.length - 1].faceUp) {
pile[pile.length - 1].faceUp = true;
addScore('TAB_FLIP');
}
}
// Double-click / double-tap: auto-move the top card of src to a foundation
function autoMoveToFoundation(src) {
let card = null;
if (src.type === 'waste') {
if (state.waste.length === 0) {
return false;
}
card = state.waste[state.waste.length - 1];
} else if (src.type === 'tableau') {
const pile = state.tableau[src.col];
if (pile.length === 0) {
return false;
}
src.idx = pile.length - 1; // ensure we're trying to move the top card
card = pile[src.idx];
if (!card.faceUp) {
return false;
}
}
if (!card) {
return false;
}
const fi = findBestFoundation(card);
if (fi === -1) {
return false;
}
undoState = deepClone(state);
commitMove(src, [cloneCard(card)], { type: 'foundation', fi });
render();
checkAutoComplete();