1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- /* Create a function that takes the name of a chess piece,
- * its position and a target position. The function should return true
- * if the piece can move to the target and false if it can't.
- * Do not include pawn capture moves and en passant.
- * Do not include castling.
- * Remember to include pawns' two-square move on the second rank!
- * Look for patterns in the movement of the pieces.
- * The possible inputs are:
- * "Pawn", "Knight", "Bishop", "Rook", "Queen" and "King".
- */
- bool canMove(std::string piece, std::string current, std::string target) {
- int colDistance = abs(target[0]-current[0]);
- int rowDistance = abs(target[1]-current[1]);
- if("Pawn" == piece){
- // must stay in the same column
- if(current[0]==target[0]){
- // can move +/-2 or +/-1 from rows 7 and 2
- if(current[1]=='7' || current[1]=='2'){
- if(rowDistance==1 || rowDistance==2){
- return true;
- }
- }
- // can move +/-1 in all other rows
- else {if(rowDistance==1) {return true;}}
- }
- } // end of pawn
- else if("King"==piece){
- // the king can move +/-1 in any direction
- if(colDistance<=1 && rowDistance<=1){
- return true;
- }
- } // end of king
- else if("Queen"==piece){
- // to move diagonal the column distance and row distance MUST be the same
- if(colDistance==rowDistance){
- return true;
- }
- // to move in a line, the column distance or row distance must be 0
- if(colDistance==0 || rowDistance==0){
- return true;
- }
- } // end of Queen
- else if("Rook"==piece){
- // to move in a line, the column distance or row distance must be 0
- if(colDistance==0 || rowDistance==0){
- return true;
- }
- } // end of Rook
- else if("Bishop"==piece){
- // to move diagonal the column distance and row distance MUST be the same
- if(colDistance==rowDistance){
- return true;
- }
- } // end of Bishop
- else if("Knight"==piece){
- // knights move +2 in either row/column and +1 in column/row
- if((colDistance==2 && rowDistance==1) ||(colDistance==1 && rowDistance==2 )){
- return true;
- }
- }
- return false;
- }
|