mchess-client/lib/chess/chess_square.dart

118 lines
3.5 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mchess/chess_bloc/chess_bloc.dart';
import '../connection/ws_connection.dart';
import '../utils/chess_utils.dart';
int messageIndex = 0;
class ChessSquare extends StatelessWidget {
final ChessCoordinate coordinate;
final ChessPiece? containedPiece;
static const double pieceWidth = 200;
static const double pieceHeight = 200;
final Color color;
const ChessSquare._(
{required this.coordinate,
required this.containedPiece,
required this.color});
factory ChessSquare(ChessCoordinate coord, ChessPiece? piece) {
Color lightSquares = Colors.brown.shade50;
Color darkSquares = Colors.brown.shade400;
Color squareColor;
if (coord.row % 2 == 0) {
if (coord.column % 2 == 0) {
squareColor = darkSquares;
} else {
squareColor = lightSquares;
}
} else {
if (coord.column % 2 == 0) {
squareColor = lightSquares;
} else {
squareColor = darkSquares;
}
}
return ChessSquare._(
coordinate: coord,
containedPiece: piece,
color: squareColor,
);
}
@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;
}
return DragTarget<ChessMove>(
builder: (context, candidateData, rejectedData) {
return Container(
color: color,
width: ChessSquare.pieceWidth,
height: ChessSquare.pieceWidth,
child: BlocBuilder<ChessBloc, ChessBoardState>(
builder: (context, state) {
int allowDrags = 0;
if (ChessBloc.myColor == null) {
allowDrags = 0;
} else {
if (containedPiece == null) {
allowDrags = 0;
} else if (containedPiece!.color == ChessBloc.myColor) {
if (ChessBloc.myColor == state.newTurnColor) {
allowDrags = 1;
} else {
allowDrags = 0;
}
}
}
return 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),
maxSimultaneousDrags: allowDrags,
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: () {},
);
},
),
);
},
onAccept: (move) {
move.endSquare = coordinate;
if (move.endSquare != move.startSquare) {
ServerConnection.getInstance().send(
'mv ${move.startSquare.toString()} ${move.endSquare.toString()}');
}
},
);
}
}