Repository navigation
Expand file tree
/
Copy pathsolitaire.ts
More file actions
1588 lines (1482 loc) · 53.2 KB
/
Copy pathsolitaire.ts
File metadata and controls
1588 lines (1482 loc) · 53.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
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
#!/usr/bin/env node
// Klondike solitaire, drawn as a web page and rendered to the terminal. The
// board is a flex row of flex columns, a card is a styled <span>, and every
// move is a click or a keystroke on it.
//
// node examples/solitaire.ts (opens the new-game menu)
// node examples/solitaire.ts <deal> (skips the menu -- the speedrun door)
//
// The menu chooses one-card or three-card draw; in three-card, the flip
// fans its last three and only the top is playable.
//
// space draw from the deck (or turn it over when empty; enter draws too
// while nothing is focused)
// f pick up the flip's top card (0 works too -- the pile left of 1)
// 1-7 pick up a tableau pile's whole face-up stack, or put what you
// are holding down on it; the same number again picks up one
// card fewer, down to the top card, then the whole stack again
// arrows and tab move the focus anywhere on the board; enter picks up
// the card under it (with its stack), puts down what you are
// holding, or puts the focused card back
// s/h/d/c send that suit's ready card home -- each home takes only the
// suit that labels it, and the letters are the player's pick
// where several cards are ready at once
// a send everything that fits home
// escape lets go of what you hold u undo q quit
// n new deal r retry this deal
// (n and r mid-run ask first -- y or enter abandons, n stays)
//
// The clock starts on the first move and stops on the win; a deal's best
// time survives retries, which is what makes a deal number a speedrun.
//
// Clicking does the same: a card picks up, a pile drops, the deck deals, and
// a double-click sends a card home. The menu and the confirm dialog take
// clicks too.
import {pathToFileURL} from "node:url";
import type {Context} from "@b9g/crank";
import {renderer} from "@b9g/crank/dom";
import {jsx} from "@b9g/crank/standalone";
import {TermDOM} from "@b9g/termdom";
// ---- the deck ----------------------------------------------------------------
const SUITS = ["♠", "♥", "♦", "♣"];
const RANKS = [
"A",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"J",
"Q",
"K",
];
interface Card {
/** 1 (ace) through 13 (king). */
rank: number;
/** An index into SUITS; hearts and diamonds are the red ones. */
suit: number;
up: boolean;
}
function isRed(card: Card): boolean {
return card.suit === 1 || card.suit === 2;
}
interface Game {
/** The deal this game was shuffled from. */
number: number;
/** How many cards a turn of the stock flips: klondike's one or three. */
draw: number;
stock: Card[];
waste: Card[];
/** One pile per suit, in SUITS order, each running up from its ace. */
foundations: Card[][];
tableau: Card[][];
moves: number;
}
/** mulberry32: enough randomness for a shuffle, from a number you can keep. */
function random(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function shuffled(seed: number): Card[] {
const next = random(seed);
const deck: Card[] = [];
for (let suit = 0; suit < 4; suit++) {
for (let rank = 1; rank <= 13; rank++) {
deck.push({rank, suit, up: false});
}
}
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(next() * (i + 1));
[deck[i], deck[j]] = [deck[j], deck[i]];
}
return deck;
}
/** Every deal has a number, so a game you liked can be played again. */
function deal(number: number, draw: number): Game {
const deck = shuffled(number);
const tableau: Card[][] = [];
for (let pile = 0; pile < 7; pile++) {
const cards = deck.splice(0, pile + 1);
cards[cards.length - 1].up = true;
tableau.push(cards);
}
return {
number,
draw,
stock: deck,
waste: [],
foundations: [[], [], [], []],
tableau,
moves: 0,
};
}
function someDeal(): number {
return Math.floor(Math.random() * 100000) + 1;
}
/** A copy deep enough to hand to the undo stack. */
function clone(game: Game): Game {
const pile = (cards: Card[]) => cards.map((card) => ({...card}));
return {
number: game.number,
draw: game.draw,
stock: pile(game.stock),
waste: pile(game.waste),
foundations: game.foundations.map(pile),
tableau: game.tableau.map(pile),
moves: game.moves,
};
}
function top(cards: Card[]): Card | undefined {
return cards[cards.length - 1];
}
// ---- the rules ---------------------------------------------------------------
/** A foundation takes its suit's ace first, and then that suit in order. */
function fitsFoundation(card: Card, foundation: Card[]): boolean {
const under = top(foundation);
if (!under) {
return card.rank === 1;
}
return under.suit === card.suit && under.rank === card.rank - 1;
}
/** A tableau pile takes a king on nothing, and descending alternating colours. */
function fitsTableau(card: Card, pile: Card[]): boolean {
const under = top(pile);
if (!under) {
return card.rank === 13;
}
return (
under.up && isRed(under) !== isRed(card) && under.rank === card.rank + 1
);
}
/** Whether the cards from `index` down form a run that moves as one. */
function isRun(pile: Card[], index: number): boolean {
if (index < 0 || index >= pile.length || !pile[index].up) {
return false;
}
for (let i = index; i < pile.length - 1; i++) {
const card = pile[i];
const next = pile[i + 1];
if (
!next.up || isRed(card) === isRed(next) || card.rank !== next.rank + 1
) {
return false;
}
}
return true;
}
/** The deepest card of a pile that can be picked up with everything below it. */
function runStart(pile: Card[]): number {
let index = pile.length - 1;
while (index > 0 && isRun(pile, index - 1)) {
index--;
}
return index;
}
type Held =
{kind: "waste"} |
{kind: "foundation"; index: number} |
{kind: "tableau"; pile: number; index: number} |
null;
/** The cards a hold is carrying, top of the run first in board order. */
function heldCards(game: Game, held: Held): Card[] {
if (!held) {
return [];
}
if (held.kind === "waste") {
const card = top(game.waste);
return card ? [card] : [];
}
if (held.kind === "foundation") {
const card = top(game.foundations[held.index]);
return card ? [card] : [];
}
return game.tableau[held.pile].slice(held.index);
}
/** Take the held cards off the board. The caller has already placed them. */
function lift(game: Game, held: Held): void {
if (!held) {
return;
}
if (held.kind === "waste") {
game.waste.pop();
} else if (held.kind === "foundation") {
game.foundations[held.index].pop();
} else {
const pile = game.tableau[held.pile];
pile.length = held.index;
// The card a moved run was sitting on turns face up.
const exposed = top(pile);
if (exposed && !exposed.up) {
exposed.up = true;
}
}
}
type Target =
{kind: "tableau"; pile: number} | {kind: "foundation"; index: number};
/** Play the held cards onto a target, or report that they do not go there. */
function play(game: Game, held: Held, target: Target): boolean {
const cards = heldCards(game, held);
if (cards.length === 0) {
return false;
}
if (target.kind === "foundation") {
// A foundation takes one card, and only ever the last of a run.
if (cards.length !== 1) {
return false;
}
if (target.index !== cards[0].suit) {
return false;
}
if (!fitsFoundation(cards[0], game.foundations[target.index])) {
return false;
}
lift(game, held);
game.foundations[target.index].push(cards[0]);
} else {
if (held?.kind === "tableau" && held.pile === target.pile) {
return false;
}
if (!fitsTableau(cards[0], game.tableau[target.pile])) {
return false;
}
lift(game, held);
game.tableau[target.pile].push(...cards);
}
game.moves++;
return true;
}
/** The foundation a single card belongs on, if it is ready for it. */
function foundationFor(game: Game, card: Card): number | null {
// Each foundation belongs to the suit that labels it, so a card has
// exactly one legal home and the row always reads true.
return fitsFoundation(card, game.foundations[card.suit]) ? card.suit : null;
}
/** Turn a card from the stock, or turn the whole waste back over. */
function draw(game: Game): boolean {
if (game.stock.length > 0) {
for (let i = 0; i < game.draw && game.stock.length > 0; i++) {
const card = game.stock.pop()!;
card.up = true;
game.waste.push(card);
}
game.moves++;
return true;
}
if (game.waste.length === 0) {
return false;
}
while (game.waste.length > 0) {
const card = game.waste.pop()!;
card.up = false;
game.stock.push(card);
}
game.moves++;
return true;
}
/** Send every card that is ready to a foundation, until none is. Returns moves. */
function autoplay(game: Game): number {
let played = 0;
for (let progress = true; progress;) {
progress = false;
const sources: Held[] = [{kind: "waste"}];
for (let pile = 0; pile < 7; pile++) {
const cards = game.tableau[pile];
if (cards.length > 0) {
sources.push({kind: "tableau", pile, index: cards.length - 1});
}
}
for (const source of sources) {
const card = heldCards(game, source)[0];
if (!card) {
continue;
}
const index = foundationFor(game, card);
if (index === null) {
continue;
}
play(game, source, {kind: "foundation", index});
played++;
progress = true;
}
}
return played;
}
function won(game: Game): boolean {
return game.foundations.every((pile) => pile.length === 13);
}
// ---- the page ----------------------------------------------------------------
// The game mounts onto a TermDOM it is handed, so the demo recorder can drive
// it as easily as the command line does.
let term: TermDOM;
let document: TermDOM["document"];
let opening: number;
let startInMenu: boolean;
/** How big a card is: the terminal's size decides, through the tiers below. */
interface Tier {
width: number;
height: number;
gap: number;
}
const TIERS = {
compact: {width: 4, height: 3, gap: 1},
roomy: {width: 5, height: 3, gap: 2},
grand: {width: 7, height: 5, gap: 3},
} as const;
const ROOMY_MIN_WIDTH = 64;
const GRAND_MIN_WIDTH = 96;
const GRAND_MIN_HEIGHT = 32;
const HINT_MIN_HEIGHT = 20;
/**
* The face of a card `depth` cards under the top one, from the top face
* down five units of each channel a card, so the thirteenth is still a
* cream and not a grey.
*/
function faceShade(depth: number): string {
const step = Math.min(depth, 12) * 5;
const hex = (channel: number) =>
(channel - step).toString(16).padStart(2, "0");
return `#${hex(0xf0)}${hex(0xf0)}${hex(0xe6)}`;
}
/** The focus blue, darkened by depth the way faceShade darkens the cream. */
function focusShade(depth: number): string {
const step = Math.min(depth, 12) * 5;
const hex = (channel: number) =>
(channel - step).toString(16).padStart(2, "0");
return `#${hex(0xcf)}${hex(0xe2)}${hex(0xf7)}`;
}
/**
* The focused card and every card on it, which is what a pick-up takes,
* in the focus blue, shaded by depth as the stack is.
*/
function focusShades(): string {
return Array.from({length: 13}, (_, depth) => {
const nth = depth === 12 ? `n+${depth + 1}` : String(depth + 1);
return ` .pile > .card:focus:where(:nth-last-child(${nth})),
.pile > .card:focus ~ .card:where(:nth-last-child(${nth})) { background-color: ${focusShade(depth)}; }`;
}).join("\n");
}
function depthShades(): string {
return Array.from({length: 12}, (_, i) => {
const depth = i + 1;
const nth = depth === 12 ? `n+${depth + 1}` : String(depth + 1);
return ` .fan > .card:where(:not(.down):nth-last-child(${nth})),
.pile > .card:where(:not(.down):nth-last-child(${nth})) { background-color: ${faceShade(depth)}; }`;
}).join("\n");
}
function sheet(): string {
// One set of numbers drives the stylesheet's @media blocks AND the matchMedia
// lists the component re-renders on, so the CSS widths and the drawn card
// faces can never disagree about the size of a card.
const css = (tier: Tier) => `
.card, .slot { width: ${tier.width}ch; height: ${tier.height}px; }
.number, .top .gap { width: ${tier.width}ch; }
.pile { width: ${tier.width}ch; }
.place { width: ${tier.width}ch; height: ${tier.height}px; }
.pile > .card + .card { margin-top: -${tier.height - 1}px; }
.fan > .card + .card { margin-left: -${tier.width - 3}ch; }
.top, .numbers, .board, .captions { gap: ${tier.gap}ch; }
.play { width: ${7 * tier.width + 6 * tier.gap}ch; }
`;
return `
.table { padding: 0 1ch; background-color: #06421f; color: #cfe8d8; user-select: none; }
/* The felt reaches the edges of the screen it was given. */
.table:fullscreen { padding: 0 2ch; }
/* The playfield is as wide as its seven piles, and the auto margins
center it in whatever the terminal turned out to be. */
.play { margin: 0 auto; }
.bar { display: flex; flex-direction: row; gap: 2ch; }
/* A crowded bar overflows the felt rather than shrinking its words. */
.bar span { flex-shrink: 0; }
.bar .title { color: #ffd75f; font-weight: bold; }
.bar .score { color: #9ec5ab; }
.bar .win { color: #ffd75f; font-weight: bold; }
.top { display: flex; flex-direction: row; margin-top: 1px; }
/* Region names, on the deals wide enough to teach them. */
.captions { display: flex; flex-direction: row; padding-top: 1px; color: #4d8f66; }
.caption { white-space: pre; }
/* The keys the piles answer to, over the piles they answer for. */
.numbers { display: flex; flex-direction: row; padding-top: 1px; }
.number { color: #4d8f66; }
.number.drop { color: #ffd75f; font-weight: bold; }
.board { display: flex; flex-direction: row; }
.pile { display: flex; flex-direction: column; position: relative; z-index: 0; }
.fan { display: flex; flex-direction: row; align-items: flex-start; }
/* Every place a stack lives has the same dark ground under its cards.
The pile is its own stacking context, so the place sits under the
cards and over the felt. */
.place { position: absolute; top: 0; left: 0; z-index: -1; background-color: #05381a; }
/* A card's rows are drawn, not written: the blank rows are spaces, and
collapsing them would shorten the card. Every card is whole; a pile is
cards laid over one another, each all but a row under the next, and
the flip's fan lays them over one another sideways, each all but its
index under the next; three columns, since a 10 takes them. A later
card paints over an earlier one. */
.card, .slot { white-space: pre; }
.card { background-color: #f0f0e6; color: #202020; }
.card.red { color: #c02020; }
.card.down { background-color: #1d4f8f; color: #4f82c8; }
/* A held card looks like any other. The one highlight on the board is
the focus; what is held shows in the green of the places it can go. */
.card.drop { background-color: #a9d7b7; }
/* Each card under another is a shade darker than the one over it, a
step a run of thirteen can take without reaching grey, so a fan or a
run reads as cards rather than as one field. Backs keep their blue.
The depth is in :where(), so the focus below still wins on a card
that has others on it. */
${depthShades()}
.slot { background-color: #05381a; color: #2f7a4a; }
.slot.drop { background-color: #a9d7b7; color: #205c35; }
/* The focused card is the document's focus: tab, the arrows, the
numbers and a click all move the same thing. It is light blue, and so
is every card on it, since picking it up takes them too. Suits keep
their colour. */
.card, .slot { outline: none; }
.card:focus { background-color: #cfe2f7; }
${focusShades()}
/* An empty place does not move. It takes the focus only as somewhere to
put what is held, or as the deck to turn over, and brightens its mark. */
.slot:focus { background-color: #cfe2f7; color: #2f5a80; }
/* The confirm covers the screen and centers its dialog; the board stays
visible around the box, the way a modal reads. */
/* Behind the menu or a question a game in progress fades: every colour on the felt
drops toward it, so the board reads as where you were rather than what
you are doing. Before any game is dealt, the menu has the felt to
itself. */
.fresh .play, .fresh .hint { display: none; }
.behind .card { background-color: #7a8a7e; color: #46524a; }
.behind .card.red { color: #7a4a4a; }
.behind .card.down { background-color: #24476a; color: #3a5f86; }
.behind .place, .behind .slot { background-color: #063f1e; color: #2a5a3a; }
.behind .fan > .card:not(.down):nth-last-child(2),
.behind .pile > .card:not(.down):nth-last-child(2),
.behind .fan > .card:not(.down):nth-last-child(n+3),
.behind .pile > .card:not(.down):nth-last-child(n+3) { background-color: #6f7e72; }
.behind .bar, .behind .captions, .behind .numbers, .behind .hint, .behind .number { color: #3f6a4f; }
.behind .bar .title, .behind .bar .win, .behind .number.drop { color: #8a7a3f; }
.scrim { position: fixed; top: 0; left: 0; width: 100%; height: 100%;
display: flex; align-items: center; justify-content: center; }
dialog { display: block; width: 48ch; border: 1px solid; border-color: #ffd75f;
background-color: #043016; color: #cfe8d8; padding: 1px 2ch; }
dialog .ask { color: #ffd75f; font-weight: bold; }
dialog .answers { color: #9ec5ab; padding-top: 1px; }
dialog .answers { display: flex; flex-direction: row; }
/* An answer is one flex item; keeping its width is what keeps its words
on one line. */
dialog .answers span { flex-shrink: 0; }
.pick { color: #9ec5ab; }
.pick.on { color: #ffd75f; font-weight: bold; }
.pickgap { width: 3ch; }
dialog .again { color: #7fae90; padding-top: 1px; }
dialog .sep { white-space: pre; }
dialog input { width: 12ch; }
.hint { padding-top: 1px; color: #7fae90; text-align: center; }
.hint b { color: #cfe8d8; font-weight: bold; }
.hint kbd { color: #cfe8d8; }
${css(TIERS.compact)}
@media (min-width: ${ROOMY_MIN_WIDTH}ch) { ${css(TIERS.roomy)} }
@media (min-width: ${GRAND_MIN_WIDTH}ch) and (min-height: ${GRAND_MIN_HEIGHT}) { ${css(TIERS.grand)} }
/* A short terminal spends its rows on the cards. */
@media (max-height: ${HINT_MIN_HEIGHT - 1}) { .hint { display: none; } }
`;
}
// ---- the board ---------------------------------------------------------------
// Every glyph reaches the markup through an interpolation. The jsx tag parses
// a template's RAW spans, and a runtime that reports raw text as an escape
// sequence -- Bun does, for anything outside ASCII -- puts the six characters
// of `▒` on the board instead of the hatch.
const TL = "▛";
const TR = "▜";
const BL = "▙";
const BR = "▟";
const T = "▀";
const B = "▄";
const L = "▌";
const R = "▐";
const WEAVE = "░";
const TURN_GLYPH = "↻";
const DOT = " · ";
const MIDDOT = "·";
const STAR = "★";
/** The key hints shrink with the cards, never past their own columns. */
function deckKey(t: Tier): string {
return t.width >= 7 ? "Space" : t.width >= 5 ? "Spc" : "\u2423";
}
function FlipKey({tier}: {tier: Tier}) {
if (tier.width >= 7) {
return jsx`<kbd>0</kbd>/<kbd>f</kbd>lip`;
}
if (tier.width >= 5) {
return jsx`<kbd>0</kbd>/<kbd>f</kbd>`;
}
return jsx`<kbd>0</kbd>`;
}
/** The cells FlipKey takes, which the caption row's padding needs. */
function flipKeyLength(t: Tier): number {
return t.width >= 7 ? 6 : t.width >= 5 ? 3 : 1;
}
/** A marked key, centered the way `centered` centers text. */
function CenteredKey({cap, width}: {cap: string; width: number}) {
const pad = Math.max(0, width - cap.length);
const left = Math.floor(pad / 2);
return jsx`${" ".repeat(left)}<kbd>${cap}</kbd>${" ".repeat(pad - left)}`;
}
const ARROWS_ALL = "↑↓←→";
function blank(width: number): string {
return " ".repeat(width);
}
/**
* A card back: a plate with solid half-block rails around a dithered weave,
* the way a printed back reads. A card under another shows the plate's top
* rule, so a pile of backs is ruled lines rather than pattern noise.
*/
function backRows(width: number, height: number): string[] {
return Array.from({length: height}, (_, row) => {
if (row === 0) {
return TL + T.repeat(width - 2) + TR;
}
if (row === height - 1) {
return BL + B.repeat(width - 2) + BR;
}
return L + WEAVE.repeat(width - 2) + R;
});
}
/** `text` centered in a field of `width` cells. */
function centered(text: string, width: number): string {
const pad = Math.max(0, width - text.length);
const left = Math.floor(pad / 2);
return " ".repeat(left) + text + " ".repeat(pad - left);
}
/**
* A card's face: its index across the top-left, its suit at the center on
* any card wide enough to carry one, and the mirrored index -- suit then
* rank -- reading into the bottom-right corner, the rotational symmetry of
* a real card's two indices.
*/
function faceRows(card: Card, tier: Tier): string[] {
const {width, height} = tier;
if (!card.up) {
return backRows(width, height);
}
const grid = Array.from(
{length: height},
() => Array.from({length: width}, () => " "),
);
const index = `${RANKS[card.rank - 1]}${SUITS[card.suit]}`;
for (let i = 0; i < index.length && i < width; i++) {
grid[0][i] = index[i];
}
if (width > 3) {
grid[Math.floor(height / 2)][Math.floor(width / 2)] = SUITS[card.suit];
}
// The bottom corner mirrors the top: suit then rank, reading into the
// corner -- the rotational symmetry of a real card's two indices, spelled
// by unit order rather than by turned glyphs.
const corner = `${SUITS[card.suit]}${RANKS[card.rank - 1]}`;
for (let i = 0; i < corner.length; i++) {
grid[height - 1][width - corner.length + i] = corner[i];
}
return grid.map((row) => row.join(""));
}
interface CardProps {
card: Card;
tier: Tier;
held?: boolean;
drop?: boolean;
/** The id the focus moves to it by. A card with one can take the focus. */
id?: string;
onmousedown?: (event: MouseEvent) => unknown;
onclick?: (event: MouseEvent) => unknown;
}
function CardFace({
card,
tier,
held,
drop,
id,
onmousedown,
onclick,
}: CardProps) {
const classes = ["card"];
if (!card.up) {
classes.push("down");
} else if (isRed(card)) {
classes.push("red");
}
if (held) {
classes.push("held");
} else if (drop) {
classes.push("drop");
}
const rows = faceRows(card, tier);
return jsx`
<div
class=${classes.join(" ")}
id=${id}
tabindex=${id !== undefined ? "0" : undefined}
onmousedown=${onmousedown}
onclick=${onclick}
>${rows.map((row, line) => jsx`<div key=${line}>${row}</div>`)}</div>
`;
}
/**
* An empty place on the board: the stock's turnover arrow, or a suit's home.
* Every one can take the focus, so the arrows reach it; only a `tabbable`
* one is in the Tab order, somewhere to put what is held.
*/
function Slot(
{tier, mark, drop, id, tabbable, onmousedown, onclick}: {
tier: Tier;
mark?: string;
drop?: boolean;
id?: string;
tabbable?: boolean;
onmousedown?: (event: MouseEvent) => unknown;
onclick?: (event: MouseEvent) => unknown;
},
) {
const rows = Array.from(
{length: tier.height},
(_, line) =>
line === Math.floor(tier.height / 2) && mark
? centered(mark, tier.width)
: blank(tier.width),
);
const classes = ["slot"];
if (drop) {
classes.push("drop");
}
return jsx`
<div
class=${classes.join(" ")}
id=${id}
tabindex=${id === undefined ? undefined : tabbable ? "0" : "-1"}
onmousedown=${onmousedown}
onclick=${onclick}
>${rows.map((row, line) => jsx`<div key=${line}>${row}</div>`)}</div>
`;
}
/** A run's clock, as a speedrunner reads it: m:ss. */
function clock(ms: number): string {
const seconds = Math.floor(ms / 1000);
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
}
function *App(this: Context) {
// One or three cards per turn of the stock -- chosen on the menu, kept
// for every deal after. A deal named on the command line skips the menu:
// that is the speedrunner's and the verifier's door.
let mode: 1 | 3 = 1;
let menu = startInMenu;
// Whether a game has been dealt to go back to. The first menu has none
// behind it; every later one has the game it was opened from.
let dealt = !startInMenu;
let game = deal(opening, 1);
let held: Held = null;
let history: Game[] = [];
let message = "";
// The clock runs from the first move to the win, and a best is the best
// for THIS deal -- retrying the same number is what a speedrun is.
let startedAt: number | null = null;
let finishedAt: number | null = null;
let best: {ms: number; moves: number} | null = null;
const ticker = setInterval(() => {
if (startedAt !== null && finishedAt === null) {
// The tick changes no state; the render reads the clock itself.
// eslint-disable-next-line crank/prefer-refresh-callback
this.refresh();
}
}, 1000);
this.cleanup(() => clearInterval(ticker));
// A run in progress is worth a question: n, r and q open a <dialog>
// instead of tearing the game down on one keystroke, and the dialog's
// keys are the only ones that answer while it shows.
let confirming: {question: string; yes: string; go: () => void} | null = null;
const liveRun = (): boolean =>
startedAt !== null && finishedAt === null && game.moves > 0;
// The board is a set of places: the deck, the flip, the four homes, and
// every card of every pile. A place has a source, what a hand would pick
// up there, and a target, where a hand would put a card down. The state
// of play is two things: what is held, and where the focus is. The focus
// is the document's, held by a card's element, so there is one and every
// input moves the same one.
//
// One gesture serves every input, choose(place):
// the focused card again put it back, and let the focus go
// holding a card that fits here put it down; nothing is focused after
// otherwise pick up what is here, and focus it
// A click chooses the place under the pointer and Enter the focused one.
// A number chooses a pile, with a cycle of its own. A drag is a press and
// a release on different piles, and puts the pressed card down on the
// second. A double-click on a pile sends its top card home.
interface Place {
row: "top" | "board";
col: number;
depth: number;
}
const DECK: Place = {row: "top", col: 0, depth: 0};
const FLIP: Place = {row: "top", col: 1, depth: 0};
const homePlace = (index: number): Place => ({
row: "top",
col: 3 + index,
depth: 0,
});
const boardPlace = (col: number, depth = 0): Place => ({
row: "board",
col,
depth,
});
/** The top row's occupied columns: the gap at column 2 holds nothing. */
const TOP_COLS = [0, 1, 3, 4, 5, 6];
const pileAt = (col: number): Card[] => game.tableau[col];
const getLast = (pile: Card[]): number => pile.length - 1;
const firstUp = (pile: Card[]): number => {
const index = pile.findIndex((card) => card.up);
return index < 0 ? getLast(pile) : index;
};
const topOf = (col: number): Place =>
boardPlace(col, Math.max(0, getLast(pileAt(col))));
const idAt = ({row, col, depth}: Place): string =>
row === "board"
? `pile-${col}-${depth}`
: col === 0 ? "deck" : col === 1 ? "flip" : `home-${col - 3}`;
const focused = (): Place | null => {
const id = document.activeElement?.id ?? "";
if (id === "deck") {
return DECK;
}
if (id === "flip") {
return FLIP;
}
const home = /^home-(\d)$/.exec(id);
if (home) {
return homePlace(Number(home[1]));
}
const card = /^pile-(\d)-(\d+)$/.exec(id);
if (card) {
return boardPlace(Number(card[1]), Number(card[2]));
}
return null;
};
/** The board is rendered first, so the element is there to take the focus. */
const seat = (place: Place): void => {
this.refresh();
document.getElementById(idAt(place))?.focus();
};
const unfocus = (): void => {
(document.activeElement as HTMLElement | null)?.blur();
};
/** What a hand would pick up at a place: a card, a run, or nothing. */
const sourceAt = (place: Place): Held => {
if (place.row === "top") {
if (place.col === 1) {
return top(game.waste) ? {kind: "waste"} : null;
}
if (place.col >= 3) {
const index = place.col - 3;
return game.foundations[index].length > 0
? {kind: "foundation", index}
: null;
}
return null;
}
const pile = pileAt(place.col);
// A face-down card stands for the whole face-up stack under it.
const index = pile[place.depth]?.up ? place.depth : firstUp(pile);
return pile[index]?.up && isRun(pile, index)
? {kind: "tableau", pile: place.col, index}
: null;
};
/** The place a source is picked up from: its own card, not the hit slop. */
const placeOf = (source: Held): Place =>
source?.kind === "tableau"
? boardPlace(source.pile, source.index)
: source?.kind === "foundation" ? homePlace(source.index) : FLIP;
/** Where a hand would put a card down at a place, or nowhere. */
const targetAt = (place: Place): Target | null =>
place.row === "board"
? {kind: "tableau", pile: place.col}
: place.col >= 3 ? {kind: "foundation", index: place.col - 3} : null;
const onSamePile = (a: Place, b: Place): boolean =>
a.row === b.row && a.col === b.col;
const isSame = (a: Held, b: Held): boolean =>
a !== null &&
b !== null &&
a.kind === b.kind &&
(a.kind !== "tableau" ||
(b.kind === "tableau" && a.pile === b.pile && a.index === b.index));
/** Whether a source can go on a target, by the rules of the game. */
const fits = (source: Held, drop: Target): boolean => {
const cards = heldCards(game, source);
if (cards.length === 0) {
return false;
}
if (drop.kind === "tableau") {
return (
!(source?.kind === "tableau" && source.pile === drop.pile) &&
fitsTableau(cards[0], game.tableau[drop.pile])
);
}
return (
cards.length === 1 &&
cards[0].suit === drop.index &&
fitsFoundation(cards[0], game.foundations[drop.index])
);
};
/** Back to the deal's opening position, clock unstarted, cursor down. */
const reset = (number: number): void => {
this.refresh(() => {
if (number !== game.number) {
best = null;
}
game = deal(number, mode);
history = [];
held = null;
message = "";
startedAt = null;
finishedAt = null;
});
(document.activeElement as HTMLElement | null)?.blur();
};
const guardedReset = (number: number, label: string): void => {
if (!liveRun()) {
return reset(number);
}
this.refresh(() => {
confirming = {
question: "Abandon this run?",
yes: `start ${label}`,
go: () => reset(number),
};
});
};
/** Run a move, keeping the board undoable and the hold consistent. */
const act = (change: (game: Game) => boolean): void => {
const before = clone(game);
// An illegal move is not a mistake worth a history entry.
if (!change(game)) {
return;
}
this.refresh(() => {
history.push(before);
if (history.length > 200) {
history.shift();
}
held = null;
message = "";
if (startedAt === null) {
startedAt = performance.now();
}
if (won(game) && finishedAt === null) {
finishedAt = performance.now();
const ms = finishedAt - startedAt;
if (!best || ms < best.ms) {
best = {ms, moves: game.moves};
message = `${STAR} best`;
}
}
});
};
/** A card picked up is held and focused, wherever it was picked from. */
const pickUp = (source: Held): void => {
this.refresh(() => {
held = source;
message = "";
});
seat(placeOf(source));
};
/** A card put back lies where it was, and the focus goes with it. */
const putBack = (): void => {
this.refresh(() => {
held = null;
message = "";
});
unfocus();
};
/**
* A card put down lands and lies still: nothing on the pile it joins is
* focused or lifted afterwards, by mouse or by key.
*/
const putDown = (source: Held, drop: Target): void => {
act((game) => play(game, source, drop));
unfocus();
};
/** The one gesture, at a place: put back, put down, or pick up. */
const choose = (place: Place): void => {
const source = sourceAt(place);
if (held !== null) {
if (isSame(held, source)) {
return putBack();
}