-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSolitaire.js
4399 lines (3971 loc) · 116 KB
/
Solitaire.js
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
//@ts-check
'use strict';
/* jshint esversion:6 */
import Random from './Random.js';
import {Util} from './Util.js';
const Constants = {
GAME_NAME: 'Oddstream Solitaire',
GAME_VERSION: '20.2.10.1',
SVG_NAMESPACE: 'http://www.w3.org/2000/svg',
LOCALSTORAGE_SETTINGS: 'Oddstream Solitaire Settings',
LOCALSTORAGE_GAMES: 'Oddstream Solitaire Games',
MOBILE: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
CHROME: navigator.userAgent.indexOf('Chrome/') !== -1, // also Brave, Opera
EDGE: navigator.userAgent.indexOf('Edge/') !== -1,
FIREFOX: navigator.userAgent.indexOf('Firefox/') !== -1,
CIRCLE: '\u25CF',
STAR: '\u2605',
SPADE: '\u2660', // ♠ Alt 6
CLUB: '\u2663', // ♣ Alt 5
HEART: '\u2665', // ♥ Alt 3
DIAMOND: '\u2666', // ♦ Alt 4
REDEALS_SYMBOL: '\u21BA', // Anticlockwise Open Circle Arrow
ACCEPT_NOTHING_SYMBOL: '\u00D7', // ×
ACCEPT_MARTHA_SYMBOL: '¹', // ¹
ACCEPT_INSECT_SYMBOL: '\u2263', // was 2261
// if you edit these, also edit symbols.svg if using symbol card suits
CARD_WIDTH: 60,
CARD_WIDTH_STACKED: Math.round(60/2), // used to stack Waste cards
CARD_HEIGHT: 90,
CARD_HEIGHT_STACKED: Math.round(90/3), // used to stack Waste cards
CARD_RADIUS: 4,
DEFAULT_STACK_FACTOR_Y: (10.0/3.0),
DEFAULT_STACK_FACTOR_X: 2.0,
MAX_STACK_FACTOR: 10,
FACEDOWN_STACK_WIDTH: Math.round(60/6),
FACEDOWN_STACK_HEIGHT: Math.round(90/9),
cardValues: 'Joker A 2 3 4 5 6 7 8 9 10 J Q K'.split(' '),
cardValuesEnglish: 'Joker Ace 2 3 4 5 6 7 8 9 10 Jack Queen King'.split(' '),
};
const suitColors = new Map([
[Constants.CIRCLE, 'purple'],
[Constants.STAR, 'purple'],
[Constants.SPADE, 'black'],
[Constants.CLUB, 'black'],
[Constants.HEART, 'red'],
[Constants.DIAMOND, 'red']
]);
// if ( !(Constants.CHROME || Constants.EDGE || Constants.FIREFOX) )
// window.alert(`Browser (${navigator.userAgent}) not supported`);
// else if ( !window.PointerEvent )
// window.alert('Pointer events not supported');
class Baize {
constructor() {
this.ele = /** @type {unknown} */(document.getElementById('baize'));
this.ele = /** @type {SVGSVGElement} */(this.ele);
/** @private @type {number} */ this.borderWidth_ = 0;
/** @private @type {number} */ this.gutsWidth_ = 0;
/** @type {number} */ this.width = 0;
/** @type {number} */ this.height = 0;
this.ele.querySelectorAll('g>rect').forEach( r => {
// let x = Number.parseFloat(r.getAttribute('x'));
let x = Number(r.getAttribute('x'))
x = 10 + (x * 67);
// let y = Number.parseFloat(r.getAttribute('y'));
let y = Number(r.getAttribute('y'))
y = 10 + (y * 100);
Util.setAttributesNS(r, {
x: x,
y: y,
width: String(Constants.CARD_WIDTH),
height: String(Constants.CARD_HEIGHT),
rx: String(Constants.CARD_RADIUS),
ry: String(Constants.CARD_RADIUS)
});
if ( x > this.gutsWidth_ ) {
this.gutsWidth_ = x;
}
});
this.gutsWidth_ += Constants.CARD_WIDTH + 10;
this.setBox_();
window.addEventListener('orientationchange', this.onOrientationChange.bind(this));
}
/**
* @private
* @param {number} b positive or negative border width
*/
adjustBorder_(b) {
this.ele.querySelectorAll('g>rect,g>text').forEach( r => {
if ( r.hasAttribute('x') ) {
let x = Number.parseInt(r.getAttribute('x'), 10) || 0;
r.setAttributeNS(null, 'x', String(x + b));
}
});
piles.forEach( cc => {
cc.pt.x += b;
cc.cards.forEach( c => {
c.pt.x += b;
c.position0();
});
});
}
/**
* @private
*/
setBox_() {
// console.warn(window.screen.orientation, window.screen.width, window.screen.height);
this.width = this.gutsWidth_;
this.height = Math.max(1200,window.screen.height);
if ( window.screen.width > window.screen.height ) {
// landscape, add a border if guts are narrow
const thresholdWidth = 1000;
if ( this.gutsWidth_ < thresholdWidth ) {
this.borderWidth_ = (thresholdWidth - this.gutsWidth_) / 2;
this.adjustBorder_(this.borderWidth_);
this.width = thresholdWidth;
}
}
// set viewport (visible area of SVG)
Util.setAttributesNS(this.ele, {
width: String(this.width),
height: String(this.height),
viewBox: `0 0 ${this.width} ${this.height}`,
preserveAspectRatio: 'xMinYMin slice'
});
}
onOrientationChange() {
if ( this.borderWidth_ ) {
this.adjustBorder_(-this.borderWidth_);
this.borderWidth_ = 0;
}
this.setBox_();
piles.forEach( pile => {
pile.cards.forEach( c => {
c.buildCard_();
});
});
allAvailableMoves(); // repaint moveable cards
}
/**
* Move card to end of baize so it appears on top of other cards
* Should be using SVG z-index to do this, but it's not implemented
* @param {Card} c
*/
elevateCard(c) {
if ( c.g !== this.ele.lastChild )
this.ele.appendChild(c.g);
}
}
const /** Array<Pile> */piles = [];
let /** @type {KeyFocus} */keyFocus = null;
const baize = new Baize;
let undoStack = /* @type {Saved[]} */([]); // can't be a const because we load game
/**
* Move a number of cards from this stack to another stack
* @param {!Pile} from
* @param {!Pile} to
* @param {!number} n
*/
function moveCards(from, to, n) {
Util.play(1 == n ? 'move1' : 'move2');
undoPush()
if ( 0 == n ) {
console.error('moveCards(0)');
} else if ( 1 == n && from.cards.length > 0 ) {
const c = from.pop();
to.push(c);
} else {
const tmp = [];
while ( n > 0 ) {
if ( from.peek() ) {
tmp.push(from.pop());
}
n = n - 1;
}
while ( tmp.length ) {
to.push(tmp.pop());
}
}
robot();
}
function undoCounter() {
let ele = document.getElementById('moveCounter');
if ( ele ) {
ele.innerHTML = String(undoStack.length);
}
}
function undoPush() {
const sv = new Saved();
undoStack.push(sv);
undoCounter();
}
/**
* @return {Saved}
*/
function undoPop() {
const sv = undoStack.pop();
undoCounter();
return sv;
}
function undoReset() {
undoStack.length = 0;
undoCounter();
}
window.doundo = function() {
if ( undoStack.length == 0 ) {
displayToast('nothing to undo');
return;
}
Util.play('undo');
const /* @type {Saved} */saved = undoPop();
// make a cache of all the cards to avoid destroying/creating them
const cache = /** @type {Card[]} */([]);
for ( const pile of piles ) {
for ( const c of pile.cards ) {
cache.push(c)
}
}
console.assert(saved.seed==GSRN.seed);
for ( let i=0; i<piles.length; i++ ) {
piles[i].load3(cache, saved.piles[i]); // calls Card.destructor
}
if ( saved.hasOwnProperty('savedPosition') ) {
GSRN.savedPosition = saved.savedPosition;
}
if ( saved.hasOwnProperty('redeals') ) {
stock.redeals = saved.redeals;
} else {
stock.redeals = null;
}
stock.updateRedealsSVG_();
allAvailableMoves(); // repaint moveable cards
scrunchContainers();
checkIfGameOver();
}
// https://stackoverflow.com/questions/20368071/touch-through-an-element-in-a-browser-like-pointer-events-none/20387287#20387287
function dummyTouchStartHandler(e) {/*console.log('dummy touch start');*/e.preventDefault();}
function dummyTouchMoveHandler(e) {/*console.log('dummy touch move');*/e.preventDefault();}
function dummyTouchEndHandler(e) {/*console.log('dummy touch end');*/e.preventDefault();}
class Card {
/**
* @param {!number} pack
* @param {!string} suit
* @param {!number} ordinal
* @param {!boolean} faceDown
* @param {!SVGPoint} pt
*/
constructor(pack, suit, ordinal, faceDown, pt) {
this.pack = pack;
this.ordinal = ordinal; // 1 .. 13
this.suit = suit;
this.faceDown = faceDown;
// sort uses the card id as input to locale
// padStart() ok in Chrome, Edge, Firefox
if ( this.ordinal < 10 ) {
this.id = `${pack}${suit}0${String(this.ordinal)}`;
} else {
this.id = `${pack}${suit}${String(this.ordinal)}`;
}
// console.assert(this.id.length===4);
// this.id = `${pack}${suit}${String(this.ordinal).padStart(2,'0')}`;
this.color = suitColors.get(this.suit);
this.owner = null;
this.pt = Util.newPoint(pt);
this.ptOriginal = null;
this.ptOffset = null;
this.grabbedTail = /** @type {Card[]} */(null);
this.ptOriginalPointerDown = null;
// https://stackoverflow.com/questions/33859113/javascript-removeeventlistener-not-working-inside-a-class
this.downHandler = this.onpointerdown.bind(this);
this.moveHandler = this.onpointermove.bind(this);
// this.moveHandler = debounce(this.onpointermove.bind(this), 10);
this.upHandler = this.onpointerup.bind(this);
this.cancelHandler = this.onpointercancel.bind(this);
this.overHandler = this.onpointerover.bind(this);
this.animationIds = /** @type {Number[]} */([]);
this.g = /** @type {SVGGElement} */(document.createElementNS(Constants.SVG_NAMESPACE, 'g'));
this.buildCard_();
this.position0();
this.addListeners_();
}
/**
* @returns {string}
*/
faceValue() {
return Constants.cardValues[this.ordinal];
}
/**
* @returns {string}
*/
toString() {
return this.id;
}
/**
* @private
*/
buildCard_() {
// flipping or orientation change: clear out any old child nodes
while ( this.g.hasChildNodes() )
this.g.removeChild(this.g.lastChild);
const r = document.createElementNS(Constants.SVG_NAMESPACE, 'rect');
Util.setAttributesNS(r, {
width: String(Constants.CARD_WIDTH),
height: String(Constants.CARD_HEIGHT),
rx: String(Constants.CARD_RADIUS),
ry: String(Constants.CARD_RADIUS)
});
this.g.appendChild(r);
if ( this.faceDown ) {
r.classList.add('spielkarteback');
} else {
r.classList.add('spielkarte');
const t = document.createElementNS(Constants.SVG_NAMESPACE, 'text');
t.classList.add('spielkartevalue');
Util.setAttributesNS(t, {
'x': this.ordinal === 10 ? String(Constants.CARD_WIDTH/4 + 4) : String(Constants.CARD_WIDTH/4),
'y': String(Constants.CARD_HEIGHT/4),
'text-anchor': 'middle',
'dominant-baseline': 'middle',
'fill': this.color
});
t.innerHTML = this.faceValue();
this.g.appendChild(t);
if ( Constants.MOBILE ) { // TODO get rid of magic numbers
const u = document.createElementNS(Constants.SVG_NAMESPACE, 'use');
const u_attribs = {
href: `#${this.suit}`,
height: '24',
width: '24',
fill: this.color
};
if ( rules.Cards.suit === 'BottomLeft' ) {
u_attribs.x = '4';
u_attribs.y = String((Constants.CARD_HEIGHT/3)*2);
} else if ( rules.Cards.suit === 'TopRight' ) {
u_attribs.x = String(Constants.CARD_WIDTH*0.6);
u_attribs.y = String(Constants.CARD_HEIGHT/20);
} else {
console.error('Unknown rules.Cards.suit', rules.Cards.suit);
}
Util.setAttributesNS(u, u_attribs);
this.g.appendChild(u);
} else {
const t = document.createElementNS(Constants.SVG_NAMESPACE, 'text');
t.classList.add('spielkartesuit');
const t_attribs = {
'text-anchor': 'middle',
'dominant-baseline': 'middle',
'fill': this.color
};
if ( rules.Cards.suit === 'BottomLeft' ) {
t_attribs['x'] = String(Constants.CARD_WIDTH/4);
t_attribs['y'] = String((Constants.CARD_HEIGHT/10)*9); // 90%
// t_attribs['transform'] = `rotate(180,${Constants.CARD_WIDTH/4},${(Constants.CARD_HEIGHT/10)*8})`;
} else if ( rules.Cards.suit === 'TopRight' ) {
t_attribs['x'] = String((Constants.CARD_WIDTH/4)*3); // 75%
t_attribs['y'] = String(Constants.CARD_HEIGHT/4);
} else {
console.error('Unknown rules.Cards.suit', rules.Cards.suit);
}
Util.setAttributesNS(t, t_attribs);
t.innerHTML = this.suit;
this.g.appendChild(t);
}
}
}
/**
* @private
*/
addListeners_() {
// put the event handlers on the g, but the event happens on the rect inside
// http://www.open.ac.uk/blogs/brasherblog/?p=599
// the ordinal and suit symbols use css pointer-event: none so the events pass through to their parent (the rect)
this.g.addEventListener('pointerover', this.overHandler);
this.g.addEventListener('pointerdown', this.downHandler);
this.g.addEventListener('touchstart', dummyTouchStartHandler);
this.g.addEventListener('touchmove', dummyTouchMoveHandler);
this.g.addEventListener('touchend', dummyTouchEndHandler);
}
/**
* @private
*/
removeListeners_() {
this.g.removeEventListener('pointerover', this.overHandler);
this.g.removeEventListener('pointerdown', this.downHandler);
this.g.removeEventListener('touchstart', dummyTouchStartHandler);
this.g.removeEventListener('touchmove', dummyTouchMoveHandler);
this.g.removeEventListener('touchend', dummyTouchEndHandler);
}
/**
* @private
*/
addDragListeners_() {
window.addEventListener('pointermove', this.moveHandler);
window.addEventListener('pointerup', this.upHandler);
window.addEventListener('pointercancel', this.cancelHandler);
}
/**
* @private
*/
removeDragListeners_() {
window.removeEventListener('pointermove', this.moveHandler);
window.removeEventListener('pointerup', this.upHandler);
window.removeEventListener('pointercancel', this.cancelHandler);
}
/**
* @param {PointerEvent} event
*/
onclick(event) { // shouldn't ever happen
console.error('click received directly on a card');
}
/**
* @param {PointerEvent} event
*/
onpointerover(event) {
let cur = 'default';
if ( this.faceDown && this === this.owner.peek() ) {
cur = 'pointer';
} else if ( this.owner.canGrab(this) ) {
if ( settings.autoPlay )
cur = 'pointer';
else
cur = 'grab';
}
// .children is an HTMLCollection
// const coll = this.g.children;
// for ( const ch of this.g.children ) { Symbol.Iterator not supported in Edge
// for ( let i=0; i<coll.length; i++ ) {
// const ch = coll.item(i);
// const ch = coll[i]; // HTMLCollection can be treated as an array
// ch.style.cursor = cur;
// }
for ( let ch=this.g.firstChild; ch; ch=ch.nextSibling ) {
ch.style.cursor = cur;
}
}
/**
* Takes the event coords from a DOM event and returns an SVG point
* The PointerEvent contains several x,y coords; choice of client, offset, (page), (layer), screen, and (x, y)
* @private
* @param {PointerEvent} event
* @returns {SVGPoint}
*/
getPointerPoint_(event) {
return Util.DOM2SVG(event.clientX, event.clientY);
}
/**
* @param {PointerEvent} event
* @returns {boolean}
*/
onpointerdown(event) {
Util.absorbEvent(event);
if ( keyFocus ) {
keyFocus.mark(false);
keyFocus = null;
}
/*
https://developer.mozilla.org/en-US/docs/Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent#Event_order
touchstart
zero or more touchmove events
touchend
mousemove
mousedown
mouseup
click
... so Firefox sends a "touch" event followed by a "mouse" event, which we interpret as two separate events
... so we need to stifle the second event
... event.preventDefault() and/or event.preventDefault(event) don't stop it
... Chrome and Edge don't do this
*/
if ( Constants.FIREFOX ) {
if ( this.owner.lastEvent ) {
if ( event.pointerType !== this.owner.lastEvent.pointerType && event.timeStamp < this.owner.lastEvent.timeStamp + 1000 ) {
console.log('stifle Firefox event');
return false;
}
}
this.owner.lastEvent = event;
}
if ( event.pointerType === 'mouse' ) {
if ( !(event.button === 0) ) {
console.log('don\'t care about mouse button', event.button);
return false;
}
}
if ( this.animationIds.length ) {
console.warn('clicking on a moving card', this.id);
return false;
}
if ( this.grabbedTail ) {
console.warn('grabbing a grabbed card', this.id);
return false;
}
// this.g.setPointerCapture(event.pointerId);
this.ptOriginalPointerDown = this.getPointerPoint_(event);
this.grabbedTail = this.owner.canGrab(this);
if ( !this.grabbedTail ) {
this.shake();
return false;
}
this.grabbedTail.forEach( c => {
c.markGrabbed();
c.ptOriginal = Util.newPoint(c.pt);
c.ptOffset = Util.newPoint(
this.ptOriginalPointerDown.x - c.pt.x,
this.ptOriginalPointerDown.y - c.pt.y
);
baize.elevateCard(c);
});
this.addDragListeners_();
return false;
}
/**
* Scale the SVGPoint (just created from a PointerEvent) into the viewBox
* There's probably a smarter way of doing this using some obscure API
* @private
* @param {SVGPoint} pt
*/
scalePointer_(pt) {
const r = baize.ele.getBoundingClientRect();
const w = r.right - r.left;
const h = r.bottom - r.top;
const xFactor = baize.width/w;
const xMoved = pt.x - this.ptOriginalPointerDown.x;
const xMovedScaled = Math.round(xMoved * xFactor);
const yFactor = baize.height/h;
const yMoved = pt.y - this.ptOriginalPointerDown.y;
const yMovedScaled = Math.round(yMoved * yFactor);
// console.log(xFactor, ':', this.ptOriginalPointerDown.x, pt.x, xMoved, xMovedScaled);
// console.log(yFactor, ':', this.ptOriginalPointerDown.y, pt.y, yMoved, yMovedScaled);
pt.x = this.ptOriginalPointerDown.x + xMovedScaled;
pt.y = this.ptOriginalPointerDown.y + yMovedScaled;
}
/**
* @param {PointerEvent} event
* @returns {boolean}
*/
onpointermove(event) {
Util.absorbEvent(event);
const ptNew = this.getPointerPoint_(event);
this.scalePointer_(ptNew);
this.grabbedTail.forEach( c => {
c.position1(ptNew.x - c.ptOffset.x, ptNew.y - c.ptOffset.y);
// console.assert(c.ptOffset.x===ptNew.x - c.pt.x);
// console.assert(c.ptOffset.y===ptNew.y - c.pt.y);
});
return false;
}
/**
* @param {PointerEvent} event
* @returns {boolean}
*/
onpointerup(event) {
Util.absorbEvent(event);
// this.g.releasePointerCapture(event.pointerId);
const ptNew = this.getPointerPoint_(event);
const ptNewCard = Util.newPoint(
ptNew.x - this.ptOffset.x,
ptNew.y - this.ptOffset.y
);
if ( Util.nearlySamePoint(ptNewCard, this.ptOriginal) ) {
// console.log('nearly same point', ptNewCard, this.ptOriginal);
this.grabbedTail.forEach( c => {
c.position1(c.ptOriginal.x, c.ptOriginal.y);
});
// a click on a card just sends the click to it's owner, so we do that directly
// console.log('simulate a click');
this.owner.onclick(this);
} else {
const pile = this.getNewOwner();
if ( pile ) {
this.moveTail(pile);
} else {
this.grabbedTail.forEach( c => {
c.animate(c.ptOriginal);
});
}
}
this.removeDragListeners_();
this.grabbedTail.forEach( c => {
c.unmarkGrabbed();
});
this.grabbedTail = null;
return false;
}
/**
* @param {PointerEvent} event
*/
onpointercancel(event) {
console.warn('pointer cancel', event);
if ( this.grabbedTail ) {
this.grabbedTail.forEach( c => c.animate(c.ptOriginal) );
}
this.grabbedTail = null;
this.removeDragListeners_();
}
/**
*/
flipUp() {
if ( this.faceDown ) {
this.faceDown = false;
this.buildCard_();
} else {
console.warn(this.id, 'is already up');
}
}
/**
*/
flipDown() {
if ( !this.faceDown ) {
this.faceDown = true;
this.buildCard_();
} else {
console.warn(this.id, 'is already down');
}
}
/**
* Use SVG transform to position this card on the baize
*/
position0() {
// console.assert(this.pt.x !== undefined);
// console.assert(this.pt.y !== undefined);
this.g.setAttributeNS(null, 'transform', `translate(${this.pt.x} ${this.pt.y})`);
}
/**
* Use SVG transform to position this card on the baize
* @param {number=} x
* @param {number=} y
*/
position1(x, y) {
this.pt.x = x;
this.pt.y = y;
this.position0();
}
/**
* @param {number} x
* @returns {!number}
* @private
*/
smootherstep_(x) {
return ((x) * (x) * (x) * ((x) * ((x) * 6 - 15) + 10));
}
/**
* Animate this card to a new position
* Designed to be invoked when card is already mid-animation;
* the card will swerve to a new destination
*
* @param {SVGPoint} ptTo
*/
animate(ptTo) {
// http://sol.gfxile.net/interpolation
/*
for (i = 0; i < N; i++)
{
v = i / N;
v = SMOOTHSTEP(v);
X = (A * v) + (B * (1 - v));
}
N.B. this will animate cards backwards
*/
const steps = [0,50,40,30,20,10]; // index will be 1..5
/**
* @param {number} timestamp
*/
const step_ = (timestamp) => {
const v = this.smootherstep_(i / N);
const x = Math.round((ptFrom.x * v) + (ptTo.x * (1 - v)));
const y = Math.round((ptFrom.y * v) + (ptTo.y * (1 - v)));
this.g.setAttributeNS(null, 'transform', `translate(${x} ${y})`);
/*
Tried using smaller number of steps for short distances,
to pep up the waste pile animation
but it doesn't look right
*/
i -= N/steps[settings.aniSpeed];
if ( i > 0 ) {
this.animationIds.push(window.requestAnimationFrame(step_));
} else {
if ( x !== this.pt.x || y !== this.pt.y ) {
this.position0();
}
this.animationIds.length = 0;
}
};
const ptFrom = Util.newPoint(this.pt);
Util.copyPoint(this.pt, ptTo); // update final pos immediately in case we're interrupted
const N = Util.getDistance(ptFrom, ptTo);
let i = N;
if ( this.animationIds.length ) {
waitForCard(this)
// .then( (value) => console.log(`waited ${Math.round(value)} for ${this.id}`) )
.catch( (reason) => console.error('animate() did not wait for card', reason) );
}
if ( 0 === N ) {
// console.log('no need to animate', this.id);
} else {
this.animationIds.push(window.requestAnimationFrame(step_));
}
}
/**
*
*/
shake() {
const shake_ = (timestamp) => {
if ( --shakes > 0 ) {
let x = (shakes % 2) ? this.pt.x + shakes : this.pt.x - shakes;
this.g.setAttributeNS(null, 'transform', `translate(${x} ${this.pt.y})`);
this.animationIds.push(window.requestAnimationFrame(shake_));
} else {
this.position0();
this.animationIds.length = 0;
}
};
if ( this.animationIds.length ) {
waitForCard(this)
// .then( (value) => console.log(`waited ${Math.round(value)} for ${this.id}`) )
.catch( (reason) => console.log('shake', reason) );
}
let shakes = 6;
this.animationIds.push(window.requestAnimationFrame(shake_));
}
/**
* Move cards from this card to end of stack (the tail) to another stack
* @param {!Pile} to
*/
moveTail(to) {
const nCard = this.owner.cards.findIndex( e => e === this );
moveCards(this.owner, to, this.owner.cards.length-nCard);
// this.moveSome(to, this.owner.cards.length-nCard);
}
/**
* Calculate the overlap area (intersection) of this card and a card at pt2
* @param {!SVGPoint} pt2
* @returns {number}
* @private
*/
overlapArea_(pt2) {
const rect1 = {left:this.pt.x, top:this.pt.y, right:this.pt.x + Constants.CARD_WIDTH, bottom:this.pt.y + Constants.CARD_HEIGHT};
const rect2 = {left:pt2.x, top:pt2.y, right:pt2.x + Constants.CARD_WIDTH, bottom:pt2.y + Constants.CARD_HEIGHT};
const xOverlap = Math.max(0, Math.min(rect1.right, rect2.right) - Math.max(rect1.left, rect2.left));
const yOverlap = Math.max(0, Math.min(rect1.bottom, rect2.bottom) - Math.max(rect1.top, rect2.top));
return xOverlap * yOverlap;
}
/**
* Find an accepting Pile that this card overlaps the most
* @returns {Pile|null}
*/
getNewOwner() {
let pileMost = null;
let ovMost = 0;
for ( const dst of piles ) {
if ( this.owner === dst )
continue;
if ( this.owner.canTarget(dst) && dst.canAcceptCard(this) ) {
const tc = dst.peek();
let ov = this.overlapArea_(tc ? tc.pt : dst.pt);
if ( ov > ovMost ) {
ovMost = ov;
pileMost = dst;
}
}
}
return pileMost;
}
/**
* @param {Array<Pile>} pileList
* @returns {Pile|null}
*/
findFullestAcceptingPile(pileList) {
/**
* @param {Pile} dst
* @returns {number}
*/
const calcWeight = (dst) => {
const dstc = dst.peek();
if ( dstc && dstc.suit === this.suit ) {
return dst.cards.length + 10;
} else {
return dst.cards.length;
}
};
let pile = null;
let max = -1;
for ( const dst of pileList ) {
if ( dst === this.owner )
continue;
if ( this.owner.canTarget(dst) && dst.canAcceptCard(this) ) {
const max0 = calcWeight(dst);
if ( max0 > max ) {
max = max0;
pile = dst;
}
}
}
return pile;
}
/**
* Take Freecell for example, with four empty cells; if a tab card can
* be moved to one cell, it's the same as moving it to any other cell, so this would
* count as one potential move, not four.
*
* @returns {Number}
*/
potentialMovesToContainers() {
/**
* @param {Pile} a
* @param {Pile} b
*/
const sameContainer = (a,b) => (a.constructor.name === b.constructor.name);
console.assert(!(this.owner instanceof Foundation));
let count = 0;
[foundations,tableaux,cells].forEach( pileList => {
const dst = this.findFullestAcceptingPile(pileList);
if ( dst ) {
// moving a bottom card to an empty container of the same type is futile
if ( 0 === dst.cards.length && this.owner.cards[0] === this && sameContainer(dst, this.owner) ) {
;
} else {
count++;
if ( !(dst instanceof Cell) ) // kludge for Freecell
this.markMoveable(dst);
}
}
});
return count;
}
/**
* Get a shallow copy of tail from this card to end of stack
* @returns {!Array<Card>}
*/
getTail() {
const nCard = this.owner.cards.findIndex( e => e === this );
return this.owner.cards.slice(nCard);
}
/**
* @returns {boolean}
*/
isTopCard() {
return this.owner.peek() === this;
}
/**
* Mark this card moveable/unmoveable
* (odd logic because modalSettings may turn sensory cues flag on/off)
* @param {Pile} ccDst
*/
markMoveable(pileDst=null) {
if ( this.faceDown )
return;
if ( this.g.firstChild.localName !== 'rect' )
return;
const cl = this.g.firstChild.classList;
const UN = 'unmoveable';
if ( settings.sensoryCues ) {
if ( pileDst ) {
cl.remove(UN);
} else {
cl.add(UN); // ignored if class already there
}
} else {
cl.remove(UN);
}
}
markGrabbed() {
this.g.firstChild.classList.add('grabbed');
}
unmarkGrabbed() {
this.g.firstChild.classList.remove('grabbed');
}
destructor() {
this.removeListeners_();
baize.ele.removeChild(this.g);
}
}
class Pile {
/**
* @param {!SVGPoint} pt
* @param {!SVGGElement} g
*/
constructor(pt, g) {
// g already has rect child with x, y attributes (from .guts/.html)
this.pt = pt;
this.g = g;
this.cards = /** @type {Card[]} */([]);
this.a_deal = this.g.getAttribute('deal');
this.a_accept = 0; // by default, accept anything
this.stackFactor = NaN;
this.rules = null; // set by subclasses
}
/**
* @private
* @returns {boolean}
*/
isAcceptSymbol_() {
return ( Constants.ACCEPT_NOTHING_SYMBOL === this.a_accept
|| Constants.ACCEPT_INSECT_SYMBOL === this.a_accept
|| Constants.ACCEPT_MARTHA_SYMBOL === this.a_accept );
}
/**
* Added so starting a new deal will reset accept in dynamically-set accepts (Duchess)
*/
loadAccept() {
// accept is either: