Chess.Domain.GameManager.IsCheckmate C# (CSharp) Method

IsCheckmate() public method

public IsCheckmate ( ) : bool
return bool
        public bool IsCheckmate()
        {
            if (!IsKingInCheck(TeamToMove(), _board.Squares)) return false;

            var squares = _board.Squares.SelectMany(s => s).ToList();

            var pieces = squares
                .Where(s => s.ChessPiece != null && s.ChessPiece.Team == TeamToMove())
                .Select(s => s.ChessPiece);

            var validMoves = new List<Move>();

            foreach (var chessPiece in pieces)
                validMoves.AddRange(chessPiece.GetValidMoves(_board.Squares));

            return !validMoves.Any(SavesKing);
        }

Usage Example

        public ActionResult MakeMove(long id, Move move)
        {
            var game = GetChessGame(id);
            var gameManager = new GameManager(game);

            if (!IsPlayersMove(game, CurrentUser))
                throw new Exception("It is not your turn!");

            try
            {
                var movingTeam = gameManager.TeamToMove();

                gameManager.MovePiece(move);

                if (gameManager.IsDraw())
                    gameManager.MarkGameAsDraw();
                else if (gameManager.IsCheckmate())
                    gameManager.MarkWinningTeam(movingTeam);

                UnitOfWork.Commit();

                var model = GetGameModel(game);

                return Json(model, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                throw NewMoveFailureException(move, ex);
            }
        }