Then why does he say “king me?!” Today I worked on the king moves for picoEngine. Note that I did not include castling moves yet. Without the castle moves, the king is actually one of the easiest pieces to program, as you can see:
string Moves::kingMoves(string boardPositions, int i) {
string list = “”;
vector <int> theseMoves;
string moveSquare;
string theBoard = boardPositions;
bool turn = true;
int rowNum = i/8;
int colNum = i%8;
if (rowNum > 0) {
if (theBoard[i-8] == ‘-‘ || islower(theBoard[i-8])) {
theseMoves.push_back(i-8);}
if (colNum > 0) {
if (theBoard[i-9] == ‘-‘ || islower(theBoard[i-9])) {
theseMoves.push_back(i-9);}}
if (colNum < 7) {
if (theBoard[i-7] == ‘-‘ || islower(theBoard[i-7])) {
theseMoves.push_back(i-7);}}}
if (rowNum < 7) {
if (theBoard[i+8] == ‘-‘ || islower(theBoard[i+8])) {
theseMoves.push_back(i+8);}
if (colNum < 7) {
if (theBoard[i+9] == ‘-‘ || islower(theBoard[i+9])) {
theseMoves.push_back(i+9);}}
if (colNum > 0) {
if (theBoard[i+7] == ‘-‘ || islower(theBoard[i+7])) {
theseMoves.push_back(i+7);}}}
if (colNum < 7) {
if (theBoard[i+1] == ‘-‘ || islower(theBoard[i+1])) {
theseMoves.push_back(i+1);}}
if (colNum > 0) {
if (theBoard[i-1] == ‘-‘ || islower(theBoard[i-1])) {
theseMoves.push_back(i-1);}}// Need castle moves //
for(int l=0; (unsigned)l<theseMoves.size();l++) {
int k = theseMoves[l];
if (islower(theBoard[k]) || theBoard[k] == ‘-‘) {
moveSquare = theBoard[k];
theBoard[k] = ‘K’;
theBoard[i] = ‘-‘;
if (isKingSafe(theBoard, turn)) {
char F = (char)(‘a’ + colNum);
char G = (char)(‘1’ + rowNum);
int rowNumK = k/8;
int colNumK = k%8;
char T = (char)(‘a’ + colNumK);
char U = (char)(‘1’ + rowNumK);
list = list + F + G + T + U + “,”;
}
theBoard[k] = moveSquare[0];
theBoard[i] = ‘K’;
}
}
return list;
} // End white king moves.
The key part being checking each direction to see if the space is open or occupied by the opposing team. This generates a list that is then checked to see if each move is “safe” or not. Which reminds me, I still need to finish fixing the king safety check…..
Either way, you can check out the full commit on my GitLab.
Linux – keep it simple.