code.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* Create a function that takes the name of a chess piece,
  2. * its position and a target position. The function should return true
  3. * if the piece can move to the target and false if it can't.
  4. * Do not include pawn capture moves and en passant.
  5. * Do not include castling.
  6. * Remember to include pawns' two-square move on the second rank!
  7. * Look for patterns in the movement of the pieces.
  8. * The possible inputs are:
  9. * "Pawn", "Knight", "Bishop", "Rook", "Queen" and "King".
  10. */
  11. bool canMove(std::string piece, std::string current, std::string target) {
  12. int colDistance = abs(target[0]-current[0]);
  13. int rowDistance = abs(target[1]-current[1]);
  14. if("Pawn" == piece){
  15. // must stay in the same column
  16. if(current[0]==target[0]){
  17. // can move +/-2 or +/-1 from rows 7 and 2
  18. if(current[1]=='7' || current[1]=='2'){
  19. if(rowDistance==1 || rowDistance==2){
  20. return true;
  21. }
  22. }
  23. // can move +/-1 in all other rows
  24. else {if(rowDistance==1) {return true;}}
  25. }
  26. } // end of pawn
  27. else if("King"==piece){
  28. // the king can move +/-1 in any direction
  29. if(colDistance<=1 && rowDistance<=1){
  30. return true;
  31. }
  32. } // end of king
  33. else if("Queen"==piece){
  34. // to move diagonal the column distance and row distance MUST be the same
  35. if(colDistance==rowDistance){
  36. return true;
  37. }
  38. // to move in a line, the column distance or row distance must be 0
  39. if(colDistance==0 || rowDistance==0){
  40. return true;
  41. }
  42. } // end of Queen
  43. else if("Rook"==piece){
  44. // to move in a line, the column distance or row distance must be 0
  45. if(colDistance==0 || rowDistance==0){
  46. return true;
  47. }
  48. } // end of Rook
  49. else if("Bishop"==piece){
  50. // to move diagonal the column distance and row distance MUST be the same
  51. if(colDistance==rowDistance){
  52. return true;
  53. }
  54. } // end of Bishop
  55. else if("Knight"==piece){
  56. // knights move +2 in either row/column and +1 in column/row
  57. if((colDistance==2 && rowDistance==1) ||(colDistance==1 && rowDistance==2 )){
  58. return true;
  59. }
  60. }
  61. return false;
  62. }