mchess-client/lib/chessapp/chess_square.dart

91 lines
2.6 KiB
Dart

import 'package:flutter/material.dart';
import 'package:mchess/chess_bloc/chess_bloc.dart';
import 'chess_utils.dart';
class ChessSquare extends StatelessWidget {
final ChessCoordinate coordinate;
late ChessPiece? containedPiece;
static const double pieceWidth = 200;
static const double pieceHeight = 200;
ChessSquare({required this.coordinate, this.containedPiece, super.key});
late Color color;
@override
Widget build(BuildContext context) {
double windowWidth = MediaQuery.of(context).size.width;
double windowHeight = MediaQuery.of(context).size.height;
double draggableFdbSize;
if (windowWidth < windowHeight) {
draggableFdbSize = 0.15 * windowWidth;
} else {
draggableFdbSize = 0.15 * windowHeight;
}
color = _getSquareColor(coordinate);
return DragTarget<ChessMove>(
builder: (context, candidateData, rejectedData) {
return Container(
color: color,
width: ChessSquare.pieceWidth,
height: ChessSquare.pieceWidth,
child: Draggable<ChessMove>(
/* We create the move with the startSquare == endSquare. The receiving widget will give the correct value to end square. */
data: ChessMove(coordinate, coordinate, containedPiece),
feedback: FractionalTranslation(
translation: const Offset(-0.5, -0.75),
child: SizedBox(
height: draggableFdbSize,
width: draggableFdbSize,
child: containedPiece),
),
childWhenDragging: Container(),
dragAnchorStrategy: pointerDragAnchorStrategy,
child: containedPiece ?? Container(),
onDragCompleted: () {},
onDragStarted: () {},
),
);
},
onWillAccept: (move) {
print('onWillAccept');
return true;
},
onAccept: (move) {
move.endSquare = coordinate;
ChessBloc().add(PieceMoved(
startSquare: move.startSquare,
endSquare: move.endSquare,
));
},
);
}
Color _getSquareColor(ChessCoordinate coordinate) {
Color lightSquares = Colors.brown.shade50;
Color darkSquares = Colors.brown.shade400;
Color squareColor;
if (coordinate.row % 2 == 0) {
if (coordinate.column % 2 == 0) {
squareColor = darkSquares;
} else {
squareColor = lightSquares;
}
} else {
if (coordinate.column % 2 == 0) {
squareColor = lightSquares;
} else {
squareColor = darkSquares;
}
}
return squareColor;
}
}