/// <summary> /// Tries to perfrom a move. Will send any diagnostic messages to user if failed. /// Will perform the move if it's valid. /// </summary> /// <param name="err">This string will hold any error messages if the move fails</param> /// <param name="piece">The piece being moved</param> /// <param name="to">The world location of the move target</param> /// <returns>True if the move is legal</returns> public bool TryMove(ref string err, BaseChessPiece piece, Point2D to) { Point2D p2 = WorldToBoard(to); if (piece == null) { err = "You must select a piece for your move"; return(false); } if (!piece.CanMoveTo(p2, ref err)) { return(false); // Invalid move } if (piece.IsCastle(p2)) { // This move is making a castle. All needed verification is made by the AllowCastle() function. Rook rook = piece as Rook; if (rook == null) { rook = this[p2] as Rook; } m_IsMoving = true; rook.Castle(); return(true); } Move move = new Move(piece, p2); ApplyMove(move); // bool ok = !IsCheck( piece.Color ) || IsCheckMate( piece.EnemyColor ); bool ok = !IsCheck(piece.Color); UndoMove(move); if (ok) { m_IsMoving = true; piece.MoveTo(move); foreach (BaseChessPiece pass in m_Table.Values) { if (pass != piece) { pass.AllowEnPassantCapture = false; // Reset en passant allowance } } } else { err = "That move would put your king under check"; } return(ok); }
/// <summary> /// Tries to perfrom a move. Will send any diagnostic messages to user if failed. /// Will perform the move if it's valid. /// </summary> /// <param name="err">This string will hold any error messages if the move fails</param> /// <param name="piece">The piece being moved</param> /// <param name="to">The world location of the move target</param> /// <returns>True if the move is legal</returns> public bool TryMove( ref string err, BaseChessPiece piece, Point2D to ) { Point2D p2 = WorldToBoard( to ); if ( piece == null ) { err = "You must select a piece for your move"; return false; } if ( ! piece.CanMoveTo( p2, ref err ) ) { return false; // Invalid move } if ( piece.IsCastle( p2 ) ) { // This move is making a castle. All needed verification is made by the AllowCastle() function. Rook rook = piece as Rook; if ( rook == null ) rook = this[ p2 ] as Rook; m_IsMoving = true; rook.Castle(); return true; } Move move = new Move( piece, p2 ); ApplyMove( move ); // bool ok = !IsCheck( piece.Color ) || IsCheckMate( piece.EnemyColor ); bool ok = !IsCheck( piece.Color ); UndoMove( move ); if ( ok ) { m_IsMoving = true; piece.MoveTo( move ); foreach( BaseChessPiece pass in m_Table.Values ) { if ( pass != piece ) pass.AllowEnPassantCapture = false; // Reset en passant allowance } } else { err = "That move would put your king under check"; } return ok; }