private bool IsCheckMate(Color color) { ChessPiece[,] board = GetBoard; King king = GetKing(color); for (int i = 0; i < board.GetLength(0); i++) { for (int j = 0; j < board.GetLength(1); j++) { ChessPiece chessPiece = board[i, j]; if (chessPiece != null) { if (chessPiece.GetColor == king.GetColor) { foreach (Point move in chessPiece.GetValidMoves()) { if (chessPiece.MoveResolvesCheck(color, move)) { return(false); } } } } } } return(true); }
private void MoveChessPiece(object sender, MouseButtonEventArgs e) { Border border = (Border)sender; Border highlighted = (Border)mainWindow.FindName("highlighted"); if (highlighted != null) { int originX = Grid.GetRow(highlighted); int originY = Grid.GetColumn(highlighted); ChessPiece currentChessPiece = GetBoard[originX, originY]; if (border.Child == null || currentChessPiece.GetColor == currentTurnColor) { bool kingIsChecked = KingIsChecked(currentTurnColor); int destinationX = Grid.GetRow(border); int destinationY = Grid.GetColumn(border); if (currentChessPiece.MoveResolvesCheck(currentTurnColor, new Point(destinationX, destinationY))) { List <Point> validMoves = null; if (!KingIsChecked(currentTurnColor)) { validMoves = currentChessPiece.GetValidMoves(); } else { validMoves = currentChessPiece.GetValidMovesIfKingIsChecked(); } if (validMoves.Where(point => point.X == destinationX && point.Y == destinationY).Any()) { if (currentChessPiece.GetType().Name == "Pawn") { ((Pawn)currentChessPiece).SetHasStepped = true; } currentChessPiece.SetCoordinates = new Point(destinationX, destinationY); GetBoard[destinationX, destinationY] = GetBoard[originX, originY]; GetBoard[originX, originY] = null; currentTurnColor = currentTurnColor == Color.White ? Color.Black : Color.White; UpdateBoard(); mainWindow.UnregisterName(highlighted.Name); if (IsCheckMate(currentTurnColor)) { MessageBox.Show(currentTurnColor.ToString() + " has lost"); } } else { ColorTile(highlighted); List <Point> highlightedValidMoves = null; if (!KingIsChecked(currentTurnColor)) { highlightedValidMoves = currentChessPiece.GetValidMoves(); } else { highlightedValidMoves = currentChessPiece.GetValidMovesIfKingIsChecked(); } UnshowValidMoves(highlightedValidMoves); mainWindow.UnregisterName(highlighted.Name); } } else { ColorTile(highlighted); List <Point> highlightedValidMoves = null; if (!KingIsChecked(currentTurnColor)) { highlightedValidMoves = currentChessPiece.GetValidMoves(); } else { highlightedValidMoves = currentChessPiece.GetValidMovesIfKingIsChecked(); } UnshowValidMoves(highlightedValidMoves); mainWindow.UnregisterName(highlighted.Name); } } } }