-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPawn.cpp
More file actions
83 lines (69 loc) · 2.73 KB
/
Pawn.cpp
File metadata and controls
83 lines (69 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <string>
#include "Pawn.h"
// constructor
Pawn::Pawn(int _row, int _col, bool _isWhite, std::string _name): Piece (_row, _col, _isWhite, _name) {ptype = "Pawn";}
// destructor
Pawn::~Pawn() {std::cout << "Destroying pawn" << std::endl;}
/*
Boolean method to see if the Pawn can move to the specified location from its current location
*/
bool Pawn::isLegalMoveTo(int _row, int _col)
{ // _row, _col is the "to" location of our desired move
// Check if trying to move diagonally for capture
bool isDiagonalMove = (_col != col);
if(isWhite == true) {
if(_row <= row) // cannot move backwards or stay in same row
return false;
// Handle diagonal moves (captures only)
if (isDiagonalMove) {
if (abs(_col - col) != 1 || _row - row != 1) // must be exactly one diagonal
return false;
Piece* capturePiece = board->pieceAt(_row, _col);
if (capturePiece != nullptr && capturePiece->isWhite != isWhite) {
return true; // valid capture
}
return false; // no piece to capture diagonally
}
// Handle forward moves (non-diagonal)
if (row == 2) {
if (_row - row > 2) // can move two spaces on first move
return false;
} else {
if (_row - row > 1) // cannot move more than one row up
return false;
}
}
else // black pieces
{
if (_row >= row) // cannot move backwards or stay in same row
return false;
// Handle diagonal moves (captures only)
if (isDiagonalMove) {
if (abs(_col - col) != 1 || row - _row != 1) // must be exactly one diagonal
return false;
Piece* capturePiece = board->pieceAt(_row, _col);
if (capturePiece != nullptr && capturePiece->isWhite != isWhite) {
return true; // valid capture
}
return false; // no piece to capture diagonally
}
// Handle forward moves (non-diagonal)
if (row == 7) {
if (row - _row > 2) // can move two spaces on first move
return false;
} else {
if (row - _row > 1) // cannot move more than one row down
return false;
}
}
// For non-diagonal moves, check if path is clear and destination is empty
if (!board->isClear(row, col, _row, _col)) // are there pieces blocking this potential move?
return false;
Piece* endPiece = board->pieceAt(_row, _col); // see if there is a piece at the "to" location
if (endPiece != nullptr) {
// Forward moves cannot capture
return false;
}
return true;
}