forked from lichess-org/flutter-chessground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboard.dart
More file actions
1114 lines (1000 loc) · 37.3 KB
/
board.dart
File metadata and controls
1114 lines (1000 loc) · 37.3 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
import 'dart:async';
import 'package:chessground/src/widgets/geometry.dart';
import 'package:dartchess/dartchess.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'board_border.dart';
import 'color_filter.dart';
import 'piece.dart';
import 'highlight.dart';
import 'positioned_square.dart';
import 'animation.dart';
import 'explosion.dart';
import 'promotion.dart';
import 'shape.dart';
import 'board_annotation.dart';
import 'static_board.dart';
import '../models.dart';
import '../fen.dart';
import '../premove.dart';
import '../board_settings.dart';
/// Number of logical pixels that have to be dragged before a drag starts.
const double _kDragDistanceThreshold = 3.0;
const _kCancelShapesDoubleTapDelay = Duration(milliseconds: 200);
/// A chessboard widget.
///
/// This widget is primarily used to display a chessboard with interactive pieces.
///
/// For a view-only board, see also [StaticChessboard].
class Chessboard extends StatefulWidget with ChessboardGeometry {
/// Creates a new chessboard widget with interactive pieces.
///
/// Provide a [game] state to enable interaction with the board.
/// The [fen] string should be updated when the position changes.
const Chessboard({
super.key,
required double size,
this.settings = const ChessboardSettings(),
required this.orientation,
required this.fen,
this.opponentsPiecesUpsideDown = false,
this.lastMove,
this.squareHighlights = const IMapConst({}),
this.onTouchedSquare,
required this.game,
this.shapes,
this.annotations,
this.explosionSquares,
}) : _size = size;
/// Creates a new chessboard widget that cannot be interacted with.
///
/// Provide a [fen] string to describe the position of the pieces on the board.
/// Pieces will be animated when the position changes.
const Chessboard.fixed({
super.key,
required double size,
this.settings = const ChessboardSettings(),
required this.orientation,
required this.fen,
this.lastMove,
this.squareHighlights = const IMapConst({}),
this.onTouchedSquare,
this.shapes,
this.annotations,
this.explosionSquares,
}) : _size = size,
game = null,
opponentsPiecesUpsideDown = false;
final double _size;
/// Size of the board in logical pixels.
@override
double get size => _size - (settings.border?.width ?? 0) * 2;
/// Side by which the board is oriented.
@override
final Side orientation;
/// Settings that control the theme and behavior of the board.
final ChessboardSettings settings;
/// If `true` the opponent`s pieces are displayed rotated by 180 degrees.
final bool opponentsPiecesUpsideDown;
/// Squares to highlight on the board.
final IMap<Square, SquareHighlight> squareHighlights;
/// FEN string describing the position of the board.
final String fen;
/// Last move played, used to highlight corresponding squares.
final Move? lastMove;
/// Callback called after a square has been touched.
///
/// This will be called even when the board is not interactable, with each [PointerDownEvent] that
/// targets a square.
final void Function(Square)? onTouchedSquare;
/// Game state of the board.
///
/// If `null`, the board cannot be interacted with.
final GameData? game;
/// Optional set of [Shape] to be drawn on the board.
final ISet<Shape>? shapes;
/// Move annotations to be displayed on the board.
final IMap<Square, Annotation>? annotations;
/// Squares on which an atomic chess explosion should be shown.
///
/// Whenever this value changes to a new non-null set the board will play a
/// one-shot explosion animation on each listed square. Typically this is the
/// set of squares returned by the dartchess atomic-explosion computation
/// (capture square + all adjacent non-pawn pieces).
///
/// Set to `null` or to the same value to suppress re-triggering.
final ISet<Square>? explosionSquares;
/// Whether the pieces can be moved by one side or both.
bool get interactive => game != null && game!.playerSide != PlayerSide.none;
@override
// No need to make this class public, as it is only used internally.
// ignore: library_private_types_in_public_api
_BoardState createState() => _BoardState();
}
class _BoardState extends State<Chessboard> {
/// Pieces on the board.
Pieces pieces = {};
/// Pieces that are currently being translated from one square to another.
///
/// The key is the target square of the piece.
TranslatingPieces translatingPieces = {};
/// Pieces that are currently fading out.
FadingPieces fadingPieces = {};
/// Squares that currently have an active explosion animation.
final Set<Square> _activeExplosions = {};
/// Currently selected square.
Square? selected;
/// Last move that was played using drag and drop.
Move? _lastDrop;
/// Squares that the selected piece can premove to.
Set<Square>? _premoveDests;
/// Whether the selected piece should be deselected on the next tap up event.
///
/// This is used to prevent the deselection of a piece when the user drags it,
/// but to allow the deselection when the user taps on the selected piece.
bool _shouldDeselectOnTapUp = false;
/// Whether the premove should be canceled on the next tap up event.
///
/// This is used to prevent the premove from being canceled when the user drags
/// a piece, but to allow the cancelation when the user taps on the origin square of the premove.
bool _shouldCancelPremoveOnTapUp = false;
/// Avatar for the piece that is currently being dragged.
_DragAvatar? _dragAvatar;
/// Once a piece is dragged, holds the square id of the piece.
Square? _draggedPieceSquare;
/// Current pointer down event.
///
/// This field is reset to null when the pointer is released (up or cancel).
///
/// This is used to track board gestures, the pointer that started the drag,
/// and to prevent other pointers from starting a drag while a piece is being
/// dragged.
///
/// Other simultaneous pointer events are ignored and will cancel the current
/// gesture.
PointerDownEvent? _currentPointerDownEvent;
/// Current render box during drag.
// ignore: use_late_for_private_fields_and_variables
RenderBox? _renderBox;
/// Pointer event that started the draw mode lock.
///
/// This is used to switch to draw mode when the user holds the pointer to an
/// empty square, while drawing a shape with another finger at the same time.
PointerEvent? _drawModeLockOrigin;
/// Pointer event that started the shape drawing.
PointerEvent? _drawOrigin;
/// Double tap detection timer, used to cancel the shapes being drawn.
Timer? _cancelShapesDoubleTapTimer;
/// Avatar of the shape being drawn.
Shape? _shapeAvatar;
@override
Widget build(BuildContext context) {
final settings = widget.settings;
final colorScheme = settings.colorScheme;
final ISet<Square> moveDests =
settings.showValidMoves && selected != null && widget.game?.validMoves != null
? widget.game?.validMoves[selected!] ?? _emptyValidMoves
: _emptyValidMoves;
final Set<Square> premoveDests = settings.showValidMoves ? _premoveDests ?? {} : {};
final shapes = widget.shapes ?? _emptyShapes;
final annotations = widget.annotations ?? _emptyAnnotations;
final checkSquare = widget.game?.isCheck == true ? _getKingSquare() : null;
final premove = widget.game?.premovable?.premove;
final background = BrightnessHueFilter(
hue: widget.settings.hue,
child:
settings.border == null && settings.enableCoordinates
? widget.orientation == Side.white
? colorScheme.whiteCoordBackground
: colorScheme.blackCoordBackground
: colorScheme.background,
);
final List<Widget> highlightedBackground = [
SizedBox.square(
key: const ValueKey('board-background'),
dimension: widget.size,
child: background,
),
if (settings.showLastMove && widget.lastMove != null)
for (final square in widget.lastMove!.squares)
if (premove == null || !premove.hasSquare(square))
PositionedSquare(
key: ValueKey('${square.name}-lastMove'),
size: widget.size,
orientation: widget.orientation,
square: square,
child: SquareHighlight(details: colorScheme.lastMove),
),
if (premove != null && widget.game?.playerSide.name == widget.game?.sideToMove.opposite.name)
for (final square in premove.squares)
PositionedSquare(
key: ValueKey('${square.name}-premove'),
size: widget.size,
orientation: widget.orientation,
square: square,
child: SquareHighlight(
details: HighlightDetails(solidColor: colorScheme.validPremoves),
),
),
if (selected != null)
PositionedSquare(
key: ValueKey('${selected!.name}-selected'),
size: widget.size,
orientation: widget.orientation,
square: selected!,
child: SquareHighlight(details: colorScheme.selected),
),
for (final dest in moveDests)
PositionedSquare(
key: ValueKey('${dest.name}-dest'),
size: widget.size,
orientation: widget.orientation,
square: dest,
child: ValidMoveHighlight(
size: widget.squareSize,
color: colorScheme.validMoves,
occupied: pieces.containsKey(dest),
),
),
for (final dest in premoveDests)
PositionedSquare(
key: ValueKey('${dest.name}-premove-dest'),
size: widget.size,
orientation: widget.orientation,
square: dest,
child: ValidMoveHighlight(
size: widget.squareSize,
color: colorScheme.validPremoves,
occupied: pieces.containsKey(dest),
),
),
if (checkSquare != null)
PositionedSquare(
key: ValueKey('${checkSquare.name}-check'),
size: widget.size,
orientation: widget.orientation,
square: checkSquare,
child: CheckHighlight(size: widget.squareSize),
),
for (final MapEntry(key: square, value: highlight) in widget.squareHighlights.entries)
PositionedSquare(
key: ValueKey('${square.name}-highlight'),
size: widget.size,
orientation: widget.orientation,
square: square,
child: highlight,
),
];
final List<Widget> objects = [
for (final entry in fadingPieces.entries)
PositionedSquare(
key: ValueKey('${entry.key.name}-${entry.value}-fading'),
size: widget.size,
orientation: widget.orientation,
square: entry.key,
child: AnimatedPieceFadeOut(
duration: settings.animationDuration,
piece: entry.value,
size: widget.squareSize,
pieceAssets: settings.pieceAssets,
blindfoldMode: settings.blindfoldMode,
upsideDown: _isUpsideDown(entry.value.color),
onComplete: () {
setState(() {
fadingPieces.remove(entry.key);
});
},
),
),
for (final entry in pieces.entries)
if (!translatingPieces.containsKey(entry.key) &&
entry.key != _draggedPieceSquare &&
entry.key != widget.game?.promotionMove?.from)
PositionedSquare(
key: ValueKey('${entry.key.name}-${entry.value}'),
size: widget.size,
orientation: widget.orientation,
square: entry.key,
child: PieceWidget(
piece: entry.value,
size: widget.squareSize,
pieceAssets: settings.pieceAssets,
blindfoldMode: settings.blindfoldMode,
upsideDown: _isUpsideDown(entry.value.color),
),
),
for (final entry in translatingPieces.entries)
PositionedSquare(
key: ValueKey('${entry.key.name}-${entry.value.piece}'),
size: widget.size,
orientation: widget.orientation,
square: entry.key,
child: AnimatedPieceTranslation(
fromSquare: entry.value.from,
toSquare: entry.key,
orientation: widget.orientation,
duration: settings.animationDuration,
onComplete: () {
setState(() {
translatingPieces.remove(entry.key);
});
},
child: PieceWidget(
piece: entry.value.piece,
size: widget.squareSize,
pieceAssets: settings.pieceAssets,
blindfoldMode: settings.blindfoldMode,
upsideDown: _isUpsideDown(entry.value.piece.color),
),
),
),
for (final shape in shapes)
BoardShapeWidget(shape: shape, size: widget.size, orientation: widget.orientation),
if (_shapeAvatar != null)
BoardShapeWidget(shape: _shapeAvatar!, size: widget.size, orientation: widget.orientation),
for (final entry in annotations.entries)
BoardAnnotation(
key: ValueKey('${entry.key.name}-${entry.value.symbol}-${entry.value.color}'),
size: widget.size,
orientation: widget.orientation,
square: entry.key,
annotation: entry.value,
),
for (final square in _activeExplosions)
PositionedSquare(
key: ValueKey('${square.name}-explosion'),
size: widget.size,
orientation: widget.orientation,
square: square,
child: IgnorePointer(
child: OverflowBox(
maxWidth: widget.squareSize * 1.5,
maxHeight: widget.squareSize * 1.5,
child: ExplosionWidget(
size: widget.squareSize * 1.5,
onComplete: () {
setState(() {
_activeExplosions.remove(square);
});
},
),
),
),
),
if (settings.enableDropMoves)
...Square.values.map((square) {
return PositionedSquare(
key: ValueKey('${square.name}-drag-target'),
size: widget.size,
orientation: widget.orientation,
square: square,
child: DragTarget<Piece>(
hitTestBehavior: HitTestBehavior.opaque,
builder:
(context, candidateData, _) =>
candidateData.isNotEmpty
? Transform.scale(
scale: 2,
child: Container(
decoration: const BoxDecoration(
color: Color(0x33000000),
shape: BoxShape.circle,
),
),
)
: const SizedBox.shrink(),
onAcceptWithDetails: (details) {
final game = widget.game;
if (game == null) return;
final piece = details.data;
final backRankPawnDrop =
piece.role == Role.pawn &&
(square.rank == Rank.first || square.rank == Rank.eighth);
if (backRankPawnDrop) return;
final move = DropMove(to: square, role: details.data.role);
if (game.sideToMove == piece.color && !pieces.containsKey(square)) {
game.onMove(move, viaDragAndDrop: true);
_lastDrop = move;
} else if (game.premovable != null) {
game.premovable?.onSetPremove.call(move);
}
},
),
);
}),
];
final board = Listener(
onPointerDown: _onPointerDown,
onPointerMove: _onPointerMove,
onPointerUp: _onPointerUp,
onPointerCancel: _onPointerCancel,
child: SizedBox.square(
key: const ValueKey('board-container'),
dimension: widget.size,
child: Stack(
alignment: Alignment.topLeft,
clipBehavior: Clip.none,
children: [
if (settings.border == null &&
(settings.boxShadow.isNotEmpty || settings.borderRadius != BorderRadius.zero))
Container(
key: const ValueKey('background-container'),
clipBehavior: Clip.hardEdge,
decoration: BoxDecoration(
borderRadius: settings.borderRadius,
boxShadow: settings.boxShadow,
),
child: Stack(alignment: Alignment.topLeft, children: highlightedBackground),
)
else
...highlightedBackground,
...objects,
if (widget.game?.promotionMove != null)
PromotionSelector(
pieceAssets: settings.pieceAssets,
move: widget.game!.promotionMove!,
size: widget.size,
color: widget.game!.sideToMove,
orientation: widget.orientation,
piecesUpsideDown: _isUpsideDown(widget.game!.sideToMove),
onSelect: widget.game!.onPromotionSelection,
onCancel: () {
widget.game!.onPromotionSelection(null);
},
canPromoteToKing: widget.game!.canPromoteToKing,
),
],
),
),
);
final borderedChessboard =
settings.border != null
? BorderedChessboard(
size: widget.size,
orientation: widget.orientation,
border: settings.border!,
showCoordinates: settings.enableCoordinates,
child: board,
)
: board;
return BrightnessHueFilter(brightness: widget.settings.brightness, child: borderedChessboard);
}
@override
void initState() {
super.initState();
pieces = readFen(widget.fen);
}
@override
void dispose() {
super.dispose();
_dragAvatar?.cancel();
_cancelShapesDoubleTapTimer?.cancel();
}
@override
void didUpdateWidget(Chessboard oldBoard) {
super.didUpdateWidget(oldBoard);
if (oldBoard.settings.drawShape.enable && !widget.settings.drawShape.enable) {
_drawModeLockOrigin = null;
_drawOrigin = null;
_shapeAvatar = null;
}
if (widget.interactive == false) {
_currentPointerDownEvent = null;
_dragAvatar?.cancel();
_dragAvatar = null;
_draggedPieceSquare = null;
selected = null;
_premoveDests = null;
}
if (oldBoard.game?.sideToMove != widget.game?.sideToMove) {
_premoveDests = null;
}
// Trigger explosion animations when the set of explosion squares changes.
if (widget.explosionSquares != null && widget.explosionSquares != oldBoard.explosionSquares) {
_activeExplosions.addAll(widget.explosionSquares!);
}
if (oldBoard.fen == widget.fen) {
_lastDrop = null;
// as long as the fen is the same as before let's keep animations
return;
}
translatingPieces = {};
fadingPieces = {};
final newPieces = readFen(widget.fen);
if (widget.settings.animationDuration > Duration.zero) {
final (translatingPieces, fadingPieces) = preparePieceAnimations(
pieces,
newPieces,
lastDrop: _lastDrop,
);
this.translatingPieces = translatingPieces;
this.fadingPieces = fadingPieces;
}
_lastDrop = null;
pieces = newPieces;
}
Square? _getKingSquare() {
for (final square in pieces.keys) {
if (pieces[square]!.color == widget.game?.sideToMove && pieces[square]!.role == Role.king) {
return square;
}
}
return null;
}
/// Returns the position of the square target during drag as a global offset.
Offset? _squareTargetGlobalOffset(
Offset localPosition,
RenderBox box, {
required bool isLargeCircle,
}) {
final square = widget.offsetSquare(localPosition);
if (square == null) return null;
final localOffset = widget.squareOffset(square);
final tmpOffset = box.localToGlobal(localOffset);
return Offset(
(widget.settings.border?.width ?? 0) +
tmpOffset.dx -
(isLargeCircle ? widget.squareSize / 2 : 0),
(widget.settings.border?.width ?? 0) +
tmpOffset.dy -
(isLargeCircle ? widget.squareSize / 2 : 0),
);
}
void _onPointerDown(PointerDownEvent details) {
if (details.buttons != kPrimaryButton) return;
final square = widget.offsetSquare(details.localPosition);
if (square == null) return;
widget.onTouchedSquare?.call(square);
final Piece? piece = pieces[square];
if (widget.settings.drawShape.enable) {
if (_drawModeLockOrigin == null) {
if (piece == null) {
// Sets a lock to the draw mode if the user holds the pointer to an
// empty square
_drawModeLockOrigin = details;
// double tap on empty square to clear shapes
if (_cancelShapesDoubleTapTimer != null) {
widget.settings.drawShape.onClearShapes?.call();
_cancelShapesDoubleTapTimer?.cancel();
_cancelShapesDoubleTapTimer = null;
} else {
_cancelShapesDoubleTapTimer = Timer(_kCancelShapesDoubleTapDelay, () {
_cancelShapesDoubleTapTimer = null;
});
}
}
// selecting a piece to move should clear shapes
else if (_isMovable(piece) || _isPremovable(piece)) {
_cancelShapesDoubleTapTimer?.cancel();
widget.settings.drawShape.onClearShapes?.call();
}
}
// draw mode takes priority over play mode when the draw mode lock is set
else if (_drawModeLockOrigin!.pointer != details.pointer) {
_drawOrigin = details;
setState(() {
_shapeAvatar = Circle(
color: widget.settings.drawShape.newShapeColor,
orig: square,
scale: 0.80,
);
});
return;
}
}
if (widget.interactive == false) return;
// From here on, we only allow 1 pointer to interact with the board. Other
// pointers will cancel any current gesture.
if (_currentPointerDownEvent != null) {
_cancelGesture();
return;
}
// keep a reference to the current pointer down event to handle simultaneous
// pointer events
_currentPointerDownEvent = details;
// a piece was selected and the user taps on a different square:
// - try to move the piece to the target square
// - if the move was not possible but there is a movable piece under the
// target square, select it
if (selected != null && square != selected) {
final couldMove = _tryMoveOrPremoveTo(square);
if (!couldMove && _isMovable(piece)) {
setState(() {
selected = square;
});
} else {
setState(() {
selected = null;
_premoveDests = null;
});
}
}
// the selected piece is touched again:
// - deselect the piece on the next tap up event (as we don't want to deselect
// the piece when the user drags it)
else if (selected == square) {
_shouldDeselectOnTapUp = true;
}
// no piece was selected yet and a movable piece is touched:
// - select the piece
else if (_isMovable(piece)) {
setState(() {
selected = square;
});
}
// no piece was selected yet and a premovable piece is touched:
// - select the piece
// - make the premove destinations
else if (_isPremovable(piece)) {
setState(() {
selected = square;
_premoveDests = premovesOf(
square,
pieces,
canCastle: widget.settings.enablePremoveCastling,
);
});
}
// pointer down on empty square:
// - cancel premove
// - unselect piece
else if (widget.game?.premovable?.premove != null) {
widget.game?.premovable?.onSetPremove.call(null);
setState(() {
selected = null;
_premoveDests = null;
});
}
// there is a premove set from the touched square:
// - cancel the premove on the next tap up event
if (widget.game?.premovable?.premove case NormalMove(:final from) when from == square) {
_shouldCancelPremoveOnTapUp = true;
}
// prevent moving the piece by 2 taps when the piece shift method is drag only
if (widget.settings.pieceShiftMethod == PieceShiftMethod.drag) {
_shouldDeselectOnTapUp = true;
}
}
void _onPointerMove(PointerMoveEvent details) {
if (details.buttons != kPrimaryButton) return;
if (!mounted) return;
// draw mode takes priority over play mode when the draw mode lock is set
if (_shapeAvatar != null && _drawOrigin != null && _drawOrigin!.pointer == details.pointer) {
final distance = (details.position - _drawOrigin!.position).distance;
if (distance > _kDragDistanceThreshold) {
final square = widget.offsetSquare(details.localPosition);
if (square == null) return;
setState(() {
_shapeAvatar = _shapeAvatar!.newDest(square);
});
}
}
if (_currentPointerDownEvent == null ||
_currentPointerDownEvent!.pointer != details.pointer ||
widget.settings.pieceShiftMethod == PieceShiftMethod.tapTwoSquares) {
return;
}
final distance = (details.position - _currentPointerDownEvent!.position).distance;
if (_dragAvatar == null && distance > _kDragDistanceThreshold) {
_onDragStart(_currentPointerDownEvent!);
}
final bool isMousePointer = details.kind == PointerDeviceKind.mouse;
_dragAvatar?.update(details);
_dragAvatar?.updateSquareTarget(
_squareTargetGlobalOffset(
details.localPosition,
_renderBox!,
isLargeCircle: !isMousePointer && widget.settings.dragTargetKind == DragTargetKind.circle,
),
);
}
void _onPointerUp(PointerUpEvent details) {
if (!mounted) return;
if (_drawModeLockOrigin != null && _drawModeLockOrigin!.pointer == details.pointer) {
_drawModeLockOrigin = null;
} else if (_shapeAvatar != null &&
_drawOrigin != null &&
_drawOrigin!.pointer == details.pointer) {
widget.settings.drawShape.onCompleteShape?.call(_shapeAvatar!.withScale(1.0));
setState(() {
_shapeAvatar = null;
});
_drawOrigin = null;
return;
}
if (_currentPointerDownEvent == null || _currentPointerDownEvent!.pointer != details.pointer) {
return;
}
final square = widget.offsetSquare(details.localPosition);
// handle pointer up while dragging a piece
if (_dragAvatar != null) {
bool shouldDeselect = true;
if (square != null) {
if (square != selected) {
final couldMove = _tryMoveOrPremoveTo(square, drop: true);
// if the premove was not possible, cancel the current premove
if (!couldMove && widget.game?.premovable?.premove != null) {
widget.game?.premovable?.onSetPremove.call(null);
}
} else {
// if piece shift method is drag only we always deselect the piece after a drag
shouldDeselect = widget.settings.pieceShiftMethod == PieceShiftMethod.drag;
}
}
// if the user drags a piece outside the board, cancel the premove
else if (widget.game?.premovable?.premove != null) {
widget.game?.premovable?.onSetPremove.call(null);
}
_onDragEnd();
setState(() {
if (shouldDeselect) {
selected = null;
_premoveDests = null;
}
_draggedPieceSquare = null;
});
}
// handle pointer up while not dragging a piece
else if (selected != null) {
if (square == selected && _shouldDeselectOnTapUp) {
_shouldDeselectOnTapUp = false;
setState(() {
selected = null;
_premoveDests = null;
});
}
}
// cancel premove if the user taps on the origin square of the premove
if (_shouldCancelPremoveOnTapUp) {
if (widget.game?.premovable?.premove case NormalMove(:final from) when from == square) {
_shouldCancelPremoveOnTapUp = false;
widget.game?.premovable?.onSetPremove.call(null);
}
}
_shouldDeselectOnTapUp = false;
_shouldCancelPremoveOnTapUp = false;
_currentPointerDownEvent = null;
}
void _onPointerCancel(PointerCancelEvent details) {
if (!mounted) return;
if (_drawModeLockOrigin != null && _drawModeLockOrigin!.pointer == details.pointer) {
_drawModeLockOrigin = null;
} else if (_shapeAvatar != null &&
_drawOrigin != null &&
_drawOrigin!.pointer == details.pointer) {
setState(() {
_shapeAvatar = null;
});
_drawOrigin = null;
return;
}
if (_currentPointerDownEvent == null || _currentPointerDownEvent!.pointer != details.pointer) {
return;
}
_onDragEnd();
setState(() {
_draggedPieceSquare = null;
});
_currentPointerDownEvent = null;
_shouldCancelPremoveOnTapUp = false;
_shouldDeselectOnTapUp = false;
}
void _onDragStart(PointerEvent origin) {
final bool isMousePointer = origin.kind == PointerDeviceKind.mouse;
final square = widget.offsetSquare(origin.localPosition);
final piece = square != null ? pieces[square] : null;
final feedbackSize =
widget.squareSize * (isMousePointer ? 1 : widget.settings.dragFeedbackScale);
if (square != null && piece != null && (_isMovable(piece) || _isPremovable(piece))) {
setState(() {
_draggedPieceSquare = square;
});
_renderBox ??= context.findRenderObject()! as RenderBox;
final dragFeedbackOffsetY =
(_isUpsideDown(piece.color) ? -1 : 1) * widget.settings.dragFeedbackOffset.dy;
final Offset feedbackOffset =
feedbackSize == widget.squareSize
? Offset((-1 * feedbackSize) / 2, (-1 * feedbackSize) / 2)
: Offset(
((widget.settings.dragFeedbackOffset.dx - 1) * feedbackSize) / 2,
((dragFeedbackOffsetY - 1) * feedbackSize) / 2,
);
final targetKind =
isMousePointer && widget.settings.dragTargetKind != DragTargetKind.none
? DragTargetKind.square
: widget.settings.dragTargetKind;
final targetWidget = switch (targetKind) {
DragTargetKind.circle => Container(
key: const ValueKey('drag-target-circle'),
width: widget.squareSize * 2,
height: widget.squareSize * 2,
decoration: const BoxDecoration(color: Color(0x33000000), shape: BoxShape.circle),
),
DragTargetKind.square => Container(
key: const ValueKey('drag-target-square'),
width: widget.squareSize,
height: widget.squareSize,
decoration: const BoxDecoration(color: Color(0x33000000)),
),
DragTargetKind.none => const SizedBox.shrink(),
};
_dragAvatar = _DragAvatar(
overlayState: Overlay.of(context, debugRequiredFor: widget),
initialPosition: origin.position,
initialTargetPosition: _squareTargetGlobalOffset(
origin.localPosition,
_renderBox!,
isLargeCircle: targetKind == DragTargetKind.circle,
),
squareTargetFeedback: targetWidget,
pieceFeedback: Transform.translate(
offset: feedbackOffset,
child: PieceWidget(
piece: piece,
size: feedbackSize,
pieceAssets: widget.settings.pieceAssets,
blindfoldMode: widget.settings.blindfoldMode,
upsideDown: _isUpsideDown(piece.color),
),
),
);
}
}
void _onDragEnd() {
_dragAvatar?.end();
_dragAvatar = null;
_renderBox = null;
}
/// Cancels the current gesture and stops current selection/drag.
void _cancelGesture() {
_dragAvatar?.end();
_dragAvatar = null;
_renderBox = null;
setState(() {
_draggedPieceSquare = null;
selected = null;
});
_currentPointerDownEvent = null;
_shouldDeselectOnTapUp = false;
_shouldCancelPremoveOnTapUp = false;
}
/// Whether the piece with this color should be displayed upside down, according to the
/// widget settings.
bool _isUpsideDown(Side pieceColor) => switch (widget.settings.pieceOrientationBehavior) {
PieceOrientationBehavior.facingUser => false,
PieceOrientationBehavior.opponentUpsideDown => pieceColor == widget.orientation.opposite,
PieceOrientationBehavior.sideToPlay => widget.game?.sideToMove == widget.orientation.opposite,
};
/// Whether the piece is movable by the current side to move.
bool _isMovable(Piece? piece) {
return piece != null &&
(widget.game?.playerSide == PlayerSide.both ||
widget.game?.playerSide.name == piece.color.name) &&
widget.game?.sideToMove == piece.color;
}
/// Whether the piece is premovable by the current side to move.
bool _isPremovable(Piece? piece) {
return piece != null &&
(widget.game?.premovable != null &&
widget.game?.playerSide.name == piece.color.name &&
widget.game?.sideToMove != piece.color);
}
/// Whether the piece is allowed to be moved to the target square.
bool _canMoveTo(Square orig, Square dest) {
final validDests = widget.game?.validMoves[orig];
return orig != dest && validDests != null && validDests.contains(dest);
}
/// Whether the piece is allowed to be premoved to the target square.
bool _canPremoveTo(Square orig, Square dest) {
return orig != dest &&
premovesOf(orig, pieces, canCastle: widget.settings.enablePremoveCastling).contains(dest);
}
/// Whether the move is pawn move to the first or eighth rank.
bool _isPromoMove(Piece piece, Square targetSquare) {
final rank = targetSquare.rank;
return piece.role == Role.pawn && (rank == Rank.first || rank == Rank.eighth);
}