This is not checkers, picoEngine….

picoEngineKing

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.

Advertisements

Queen, picoEngine?

picoEngineQueen

In my most recent commit, which you can check out in full at my GitLab, I added the ability for the queen to move to the picoEngine. This completes all of the major/minor pieces of motion, and only leaves the king and pawns to complete (believe it or not, these are the hardest to do, as they have many conditional clauses).

I actually was able to hammer this out in about 15 minutes, since it really is just a combination of the rook and bishop moves with a “q” instead of the respective letters. Since it is identical to those, I wont post much of the code here. If you are wondering, however, how I add them to the header files, it looks like this in Moves.h:

#pragma once
#include <cmath>
#include <string>
using namespace std;

class Moves {

private:
char m_theBoard[64] = {‘R’,’N’,’B’,’Q’,’K’,’B’,’N’,’R’,’P’,’P’,’P’,’P’,’P’,
‘P’,’P’,’P’,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,
‘-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,’-‘,
‘-‘,’p’,’p’,’p’,’p’,’p’,’p’,’p’,’p’,’r’,’n’,’b’,’q’,’k’,’b’,’n’,’r’};

bool m_whitesTurn = true;
bool m_Kcastle = true;
bool m_Qcastle = true;
bool m_kcastle = true;
bool m_qcastle = true;
bool m_enPassant = false;
string m_enPasPawn = “”;
int m_moveSince = 0;
int m_turnCount = 0;
// Public prototypes go here
public:

// All available moves.
string available(string boardPositions, bool whoseTurn);

// Best move.
string bestMove(string boardPositions, bool whoseTurn, bool styleRandom);

// Is the king safe?
bool isKingSafe(string boardPositions, bool whoseTurn);

// Black night moves:
string nightMovesB(string boardPositions, int i);
// white night moves:
string nightMoves(string boardPositions, int i);
// Black rook moves:
string rookMovesB(string boardPositions, int i);
// white rook moves:
string rookMoves(string boardPositions, int i);
// Black bishop moves:
string bishopMovesB(string boardPositions, int i);
// white bishop moves:
string bishopMoves(string boardPositions, int i);
// Black queen moves:
string queenMovesB(string boardPositions, int i);
// white queen moves:
string queenMoves(string boardPositions, int i);

};

After adding the command option to the header file, then I can actually create it in the Moves.cpp file:

string Moves::queenMoves(string boardPositions, int i) {
————– Abridged, see commit for details. ——————-
} // End white queen moves.

Object oriented programming (oop) is a really fun way to program. The top 2 programming languages used for video games today are Java and C++, which are both oop types of programming. Since Android devices now make up more percentage of the worlds operating system than any other operating system, and most Android games are written in oop like Java and C++, that makes sense. But even most desktop games are made with these languages as well.

Linux – keep it simple.

Bishops aren’t Bums…

picoengineBishop

Believe it or not, the bishops can now move! 3 of the 6 piece types now have the complete freedom of movement that they should have on the regular board! Things seem to be making steady progress, although I still see some issues with kingSafety, so I’ll have to work on that!

There is also an issue with odd positions. If you start a new game as normal. All is well for picoEngine, and it can track moves as usual. However, if you use the interface to adjust the piece positions, picoEngine will only track the first move, subsequent moves cause an illegal exception. So that needs to be looked into. Also, picoEngine does not like Chess960!

As always, the full commit is available on GitHub, if you’d like to see how the bishops get their move on. It is very similar to the rook motion, but diagonally placed.

Linux – keep it simple.

Uh, picoEngine? I thought you said the king was safe?

kingsafe

Except he’s not. That’s right. I big technical oversight on my part allowed the king to not be safe at all!

while (boardPositions[k] == ‘*’ && notI) {

Needed to be changed to:

while (boardPositions[k] == ‘-‘ && notI) {

That’s right! A – is what my board uses for empty spaces. But the Java board I wrote for JustChessEngine used an * instead. I guess I got confused when looking at the code and put it in the wrong way! Too much copy and paste from my Java work I suppose. Either way, the king is safer now!

Linux – keep it simple.

picoEngine is such a rook-ie!

picoEngineRook

Now the rooks can move too!

While it is only a small improvement, the rooks can now also be moved by picoEngine, which is a great step forward. Overall, that leaves 2 of 6 pieces complete for motion, or about 33% complete. Technically, when that is done, the engine will be completely playable, however, much work will be needed to make it “intelligent”.

While there are probably better ways to do this, I followed a pretty simple pattern for making the rook moves:

// Up moves
bool notI = true;
int j = 1;
int vert = 8;
int k = i;
if (i < 56) {
k = i + (vert * j);
}
while (theBoard[k] == ‘-‘ && notI) {
theseMoves.push_back(k);
vert += 8;
if (k < 56) {
k = i + (vert * j);
} else {
notI = false;
}
} // While it’s empty.
if (isupper(theBoard[k])) {
theseMoves.push_back(k);
} // When there is an enemy.

// Down moves
notI = true;
j = -1;
vert = 8;
k = i;
if (i > 7) {
k = i + (vert * j);
}
while (theBoard[k] == ‘-‘ && notI) {
theseMoves.push_back(k);
vert += 8;
if (k >7) {
k = i + (vert * j);
} else {
notI = false;
}
} // While it’s empty.
if (isupper(theBoard[k])) {
theseMoves.push_back(k);
} // When there is an enemy.

That is for “up” moves, and the pattern repeats for down, left, and right. As always, you can check out the full commit on my GitLab.

Linux – keep it simple.

Make a move picoEngine….

picoEngineMoves

For the first time ever, picoEngine made it’s very own move.

While no where near as important as my children taking their first steps, it was really a monumental moment for me when picoEngine made it’s very first move using UCI commands while loaded in Arena. That’s right, after several hours of tinkering, I loaded the picoEngine into the chess application called Arena, and let it make it’s very first move!

Of course, at this point, the only thing it can move is the knight, since that’s all I’ve programmed it for, but still, it was a monumental step in the direction of C++ chess engine programming for me!

While I’ve made two chess engines in Java, for various Android apps, this is different. Not only am I programming in C++, but my goal is to use the Universal Chess Interface so my chess engine can be loaded into any chess program. That is making things a bit tough. But now that I have successfully made a move, hopefully it will be smooth sailing from here on out.

string Moves::bestMove(string boardPositions, bool whoseTurn, bool styleRandom){
string candidateList = Moves::available(boardPositions, whoseTurn);
string chosenMove = “”;
if (candidateList.size() > 0){
//if (styleRandom) {
srand((int)time(0) + candidateList.size());
int r = (rand() % (candidateList.size()/5));
for (int a = 0; a < 4; a++) {
chosenMove += candidateList[(5*r)+a];
}
//} else {

//}
}
return chosenMove;
}

The check for available moves and king safety are things we already covered, so essentially, I just needed to make it choose the best move of the ones available. In the future, this will hopefully be a weighted decision, but for now, I’m just passing a random choice of the available moves in the list, which, of course, only features the knights at present.

As always, you can check out the full commit on my GitLab.

Linux – keep it simple.

picoEngine meets Bob Seger….

nightmoves

Okay, so not really. Bob Seger once had a hit called “Night moves” which is what I just added to my picoEngine: knight moves. As always, you can check through the whole commit on my GitLab. Once again, I borrowed from my Java engine, justchess engine but had to do quite a bit of work to convert this method into C++. For instance, in Java, I make an array, but in C++ I had to set up a vector.

Overall, the code is cleaner and more compact for C++ than it was for Java. I’m not sure if it is because I am getting better, or just the language differences, but I’ll take it! I’m still a bit fuzzy about comparing signed and unsigned commits, so I have to keep editing my loops like so:

for(int l=0; (unsigned)l<theseMoves.size();l++) {

Making sure to put the parenthesis and unsigned before the integer. But, it seems to work, so I’ll go with that for now, perhaps later I can study up on it a bit more and see why this is needed.

Linux – keep it simple.

Is the king safe, picoEngine?

kingsafe

One of the really important rules of playing chess, in fact, the rule upon which the entire game hinges, is king safety. You can’t make a move that puts your king in an unsafe position. This position of unsafe-ness is referred to as ‘check’. If you can’t find a way to get out of the position of being in ‘check’, then you are in ‘checkmate’.

Of course, if you are not in ‘check’ but any move would make you so, it is called a ‘stalemate’.

Thus, you can see the absolute need for a method or function to assess if the king is in check or not. So, I borrowed a method from my previous work in Java, the justchess engine. Of course it had to be edited for C++, but since both languages are object oriented programming languages, then it wasn’t too difficult.

You can check the commit at my GitLab for the full scoop, but essentially, my method assumes that the king is safe unless proven otherwise. This saves time, because at any point, if the king is proven unsafe, or in check, it will stop recursing through the board and other pieces and return a status of false: the king is not safe.

Linux – keep it simple.

Once again, and from the top, picoEngine.

Last time I mentioned how the UCI (Universal Chess Interface) required two types of input, the FEN input, and a move by move input style. The second is rather interesting, especially for the internal chess board I have set up, because the input uses standard notation with alphanumeric characters.

startpos

Here you can see my code in action, moving the pieces of the board.

Once I figured out how to convert char (actors) to int (egers) than all was well, but doing that is harder than it seems. Especially coming from Java to C++. I would think that there was a more “intuitive” way to do this, but alas, I could not find one.

Supposedly, you could simply use it like so:

char aChar = ‘1’;

char bChar = ‘a’;

int c = aChar;

int d = bChar;

But I get strange numbers from that. Instead, I needed to do this:

char aChar = ‘1’;

char bChar = ‘d’;

int c = aChar – ‘0’;

int d = bChar – ‘a’;

To convert them to useful numbers. Now it would return 4 for d, and 1 for 1. Great huh? Then I just used some simple math:

int first =63 – ((sepVect[k].at(0) – ‘a’ + 1) + (((sepVect[k].at(1) – ‘1’) * 8) – 1));

int second =63 – ((sepVect[k].at(2) – ‘a’ + 1) + (((sepVect[k].at(3) – ‘1’) * 8) – 1));

And converted them to space numbers for my board! It was pretty easy after that, to just move the piece from the first spot to the second spot and leave a blank space behind. Be sure to check out the full code on my GitLab repository!

Linux – keep it simple.

picoEngine Meets FEN

print

One of the more interesting parts to programming chess engines, is using the UCI, Universal Chess Interface. In that interface standard are very specific settings. One of those is that engines should accept input as either move by move, or through FEN.

The FEN part was actually quite easy. Just breaking down characters of the line and figuring out what goes where. The toughest part was understanding vectors so I could do what I wanted to do. Here’s a glimps of the code:

vector<string> split(string str, char delimiter) {
vector<string> internal;
stringstream ss(str); // Turn the string into a stream.
string tok;

while(getline(ss, tok, delimiter)) {
internal.push_back(tok);
}

return internal;
}
………………………………………..Edited for space…………………………………
void inputPosition(string posString)
{
vector<string> sepVect = split(posString, ‘ ‘);
string str1 = sepVect[1];
if (sepVect[1] == “fen”)
{
// FEN board setup.
string stringBoard = “”;
string str2 = sepVect[2];
for (int i = 0; (unsigned)i < str2.length(); i++) {
char myChar = str2.at(i);
if (isdigit(myChar))
{ int imyChar = myChar – ‘0’;
for (int a = 0; a < imyChar; a++)
{ stringBoard = stringBoard + “-“; }
}
else if (isalpha(myChar))
{ stringBoard = stringBoard + myChar; }
} // end for.
int j = stringBoard.length();
for (int i = 0; i < j; i++) {
if (i < 64){ theBoard[i] = stringBoard.at(i); }
}
if (sepVect[3].at(0) == ‘w’)
{ whitesTurn = true; } else { whitesTurn = false; }
if (sepVect[4].at(0) == ‘K’)
{ Kcastle = true; } else { Kcastle = false; }
if (sepVect[4].at(1) == ‘Q’)
{ Qcastle = true; } else { Qcastle = false; }
if (sepVect[4].at(2) == ‘k’)
{ kcastle = true; } else { kcastle = false; }
if (sepVect[4].at(3) == ‘q’)
{ qcastle = true; } else { qcastle = false; }
if (sepVect[5].at(0) == ‘-‘)
{ enPassant = false;} else { enPassant = true;}
moveSince = stoi (sepVect[6]);
turnCount = stoi (sepVect[7]);
} // End FEN

I just broke down the string into vectors separated by spaces. Then in each vector, I figured out where the piece needed to go, or how many blank spaces I needed.

Now I still have to work out a few oddities, but I think this should work fairly well, and seems to have in the few test runs I’ve given it. You can check out the whole commit on my GitLab if you’d like!

Linux – keep it simple.