Fool’s Mate Friday: Suggestions, anyone?

Well, more specifically, suggestions, computer?

One of the cool things about having the built in JustChessEngine in my JustChess app, is the option to have the engine suggest a move for you. Of course, my engine has an elo rating below 300, so I’m not sure that I would take it’s advice, at least not yet. In any event, I thought it might be handy to have a button to suggest a “good” move.

jc7

You may also note that the GUI got cleaned up a bit in previous commits.

Adding the code for this was fairly easy. I already had the text at the bottom of the screen updating when you clicked on a piece, I sort of just changed that into making a query of the next “best” suggested move. Interesting to note, that this best move is based on the engine strength of 1, rather than of the strength you chose to play against.

At this point it is more or less just showing you a valid move that gains you some points on it’s own scale of value. It is not a very good at tactics.

In either event, here was the most important part of the code:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        moveOptions="";
        if (!wTurn){
            moveOptions= terminal("suggestMove,black");
        } else {
            moveOptions= terminal("suggestMove,white");
        }

        try {
            if (moveOptions.equals("K-0-0R,")) {
                chessImage[6].setBackgroundResource(R.drawable.suggested);;
            } else if (moveOptions.equals("K0-0-0,")) {
                chessImage[2].setBackgroundResource(R.drawable.suggested);;
            } else if (moveOptions.equals("k-0-0r,")) {
                chessImage[62].setBackgroundResource(R.drawable.suggested);;
            } else if (moveOptions.equals("k0-0-0,")) {
                chessImage[58].setBackgroundResource(R.drawable.suggested);;
            } else {
                String temp = String.valueOf(moveOptions.charAt(3)) +
                        String.valueOf(moveOptions.charAt(4));
                int highlightThis = Integer.parseInt(temp);
                chessImage[highlightThis].setBackgroundResource(R.drawable.suggested);
                temp = String.valueOf(moveOptions.charAt(1)) +
                        String.valueOf(moveOptions.charAt(2));
                highlightThis = Integer.parseInt(temp);
                chessImage[highlightThis].setBackgroundResource(R.drawable.suggested);
            }

        } catch (Exception e) {
            // Do nothing.
            Log.i("WJH", e.toString());
        }

        Snackbar.make(view, "JustChessEngine suggests: "+ moveOptions, Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
    }
});

I just edited the snack bar to pop up with the suggested move, and had the board highlight the squares green for it as well. The green squares clear when you make a move, weather it be the one suggested, or some other one. You can see the full commits and how I overcame the king castle suggestion problems on my GitHub.

Linux – keep it simple.

Fool’s Mate Friday: En passant checkmate!

According to legend, Gary Kasparov once checkmated via en passant in an on-line game. However, I couldn’t actually find a detailed reference to that specific game. I was, however, able to find an article that expressed the only officially logged game in which an opponent was check mated via en passant. It was a game between Gunnar Gundersen and A H Faul during a Christmas tournament in 1928. Here was the move list:

1.e4 e6 2.d4 d5 3.e5 c5 4.c3 cxd4 5.cxd4 Bb4+ 6.Nc3 Nc6 7.Nf3 Nge7 8.Bd3 O-O 9.Bxh7+ Kxh7 10.Ng5+ Kg6 11.h4 Nxd4 12.Qg4 f5 13.h5+ Kh6 14.Nxe6+ g5 15.hxg6# 1-0

enpassantcheckmate

Certainly an interesting prospect. In this case, the en passant move doesn’t actually check the king, but prevents the king from retreating from the now discovered check of the rook. In any case, en passant is a very important part of playing chess, which makes it all the more vital that I fix it in my JustChessEngine and make it usable in my JustChess game.

The fix was not an easy one, but it came down to a few mathematical errors on my part, as well as a huge technical oversight. The program used to work like this:

If doing en passant for white:

place pawn to new square (+7 for right/up, and +9 for left/up). Remove taken pawn.

However, it would end up with two white pawns and remove the attacked pawn. So I edited it to be proper, like so:

If doing en passant for white:

place pawn to new square (+9 for right/up, and +7 for left/up). Remove taken pawn. Remove pawn from old square.

So, both the math was wrong on which side to go to, but also the pawn was never “removed” from it’s old square, just a new pawn was placed where it was going to! The fix was simple in principle, complex in actuality, but you can view the whole set of changes here: https://github.com/alaskalinuxuser/app_JustChess/commit/3053591df42473577e557b860ad639485841051f

I’m just glad it’s finally fixed!

Linux – keep it simple.

Fool’s Mate Friday: One Player or Two?

It was interesting to me that white did not always move first in chess. Apparently, in 1857, a master of chess, Mr. Lowenthal made a recommendation to the First American Chess Congress that white should always move first as a rule. However, that rule was not actually enforced until sometime in the 1900’s. Supposedly, they used to toss coins to see who went first, and that player could choose either color.

red

It might also be noteworthy that the pieces were not always black or white, as some old sets used red as one of the colors. Obviously, today you can get a chess set in any style or color imaginable.

In either event, JustChess is now one or two player! You can choose to play as black or white. Currently, the game is pretty rough around the edges, with a few notable bugs. You can check out the commit at my GitHub.

At present, the JustChessEngine is not very bright, to say the least. But currently, there are issues with the moves sometimes making an erroneous change to the board. Two player mode works as expected, however, en passant still needs to be fixed.

Perhaps when I iron out those bugs, I can release a 0.1 version.

Linux – keep it simple.

Fool’s Mate Friday: Now with moving pieces!

According to the Guinness World Records, the biggest playable chess set was made in Canada in 2009, with a king that was about 4 feet tall! Try moving that chunk of wood! Fortunately for me, moving these “wooden” chess pieces doesn’t require much by way of heavy lifting!

twoplayer

It isn’t exactly a walk in the park, either though. Making this game two player and movable was actually pretty simple:

public void moveablePiece (View view) {

    // Get the clicked squares tag to see what number it is.
    int number = Integer.parseInt(view.getTag().toString());
    String played;
    if (number < 10) {
        played = "0" + String.valueOf(number);
    } else {
        played = String.valueOf(number);
    }

    if (firstClick) {

        firstClick=false;
        String myMove = tryMove + played + String.valueOf(theBoard[number]);
        Log.i("WJH", myMove);
        moveOptions= terminal("availMoves,"+String.valueOf(wTurn));

        String[] separated = moveOptions.split(",");

        if (Arrays.asList(separated).contains(myMove)) {

            String query = terminal("myMove,"+myMove);
            Log.i("WJH", query);
            drawBoardPieces();
            wTurn = !wTurn;

        }
        tryMove = "";
        myMove = "";
        mCtv.setText(moveOptions);

    } else {

        firstClick=true;
        tryMove = String.valueOf(theBoard[number]) + played;
        Log.i("WJH", tryMove);
        String query = terminal("pieceMoves,"+ String.valueOf(theBoard[number]) +
                "," + played);
        mCtv.setText(query);
    }

} // End clicked piece.

But the problem that I have now is that the method I use to move the pieces doesn’t work well with the engine when it comes to castling, promoting, or en passant. So I may need to adjust the JustChessEngine to be more of a FEN style input/output. We’ll have to see.

Linux – keep it simple.

Fool’s Mate Friday: Identifying the board square by number.

Identification please! Did you know that there have been numerous cases of mistaken identity for the masters of chess in print? There are so many that websites have even devoted entire pages to these mix ups! You can check out some good ones here, where among others, Bernhard Kagan was confused for Alexander Alekhine!

A case of mistaken identity is a bit of a problem. A problem I hope to avoid in my JustChess app. Particularly, I am referring to the pieces that you click on. My next goal of the app is to make it possible to have a human player challenge the JustChess Engine. To do so, I need the player to be able to move the pieces.

clickedjustchess

In retrospect, there may be better ways to do this, but for now, I have tagged all 64 squares of the board, and made them “clickable”. When clicked, the board now returns the tag number. This tag number can simply be cross referenced with the virtual board’s character array to find the corresponding piece. Here’s a break down of the code:

public void moveablePiece (View view) {

    // Get the clicked squares tag to see what number it is.
    int played = Integer.parseInt(view.getTag().toString());

    Log.i("WJH", "clicked sqaure "+ String.valueOf(played));
    Log.i("WJH", "clicked piece "+ theBoard[played]);
    moveOptions= terminal("availMoves,"+String.valueOf(wTurn));
    mCtv.setText(moveOptions);

} // End clicked piece.

What?! Pretty simple isn’t it. All that transpires is the clicked square (which is a view) calls this function and returns it’s own tag. The tag equates to the square number and that number is cross referenced with the board.

Now that the piece is properly identified, I can cross reference it with available moves, highlight those squares, and make it an option to move there, or not move at all. Easy right? Let’s hope so!

Linux – keep it simple.

Fool’s Mate Friday: JustChess, shaken, not stirred….

Well, I suppose the Bond reference does sound a bit out of place here, but perhaps if we break it down it will not seem to be so.

In the 1963 movie “From Russia With Love” James Bond is facing a fierce and brilliant opponent, Russian agent Kronsteen, who during the opening scene takes down the Canadian Grandmaster McAdams in a chess tournament. The point being is that Bond is not up against an imbecile, but rather a strategic genius.

Of course, Bond’s favorite drink was was a dry martini with a slice of lemon, “shaken, not stirred.” I’m not a drinking man myself, but I have come to understand that shaking the mixture actually does make a difference over stirring, according to Wikipedia. My point in using this phrase is that to make my JustChessEngine playable, I am not just going to stir it in, but shake it up a bit, as I add it to my new app: JustChess. I know, that is a very original name!

 

The first thing on the agenda was to move the launch point of the app to be an “intro” screen, where the player could choose between single player (against the JustChessEngine) or two player, one against the other. At this point, I’m planning to focus on the first, that of playing against the engine.

Be sure to stop by my GitHub and check it out:  https://github.com/alaskalinuxuser/app_JustChess

Linux – keep it simple.

Fool’s Mate Friday: Touching up the User Interface….

JustChessEngine

My uncle once told me that a good paint job will sell a bad airplane. He’s right. As an airplane mechanic, he knew the value of the planes that he worked on. At the same time, he saw customer after customer get “swindled” on a plane that looks nice on the outside.

The thing is, it’s true for apps and games as well. A really good program that doesn’t look good just isn’t as fun. Truth is, this engine app needed a little touch up in the gui department. So, while I didn’t make it pretty, I did add features to try to make it more useful.

Similar to the Beginning Chess Engine, I added a commit to allow the user to make a move by pressing the button. Simple stuff really, but up ’till now, I was doing all of my move making from the command line through the app code itself. Of course, if you can make a move, you need to be able to take it back to, so I added a commit to give the undo move method.

The flow of these move methods are pretty simple. For most moves, it checks the from space and the to space and puts an “*” (asterisk) at the from, and puts the piece that was there in the to space. The process is reversed for the undo move method.

There are a few exceptions, though, like the additional moves that are special, en passant, castle, and promotion. Those are handled by reading the input move first to see if it matches any of those scenarios, if not, then a regular move is performed.

Obviously, making moves in chess is a pretty important part of the game. The longest chess game theoretically possible is 5,949 moves, and that would be impossible to do if you couldn’t actually make any of those moves!

Linux – keep it simple.

Fool’s Mate Friday: Keeping the king safe!

bk

The word “Checkmate” in Chess comes from the Persian phrase “Shah Mat,” which means “the King is dead.”

While in the starting position, there are eight different ways to checkmate in two moves and 355 different ways to checkmate in three moves. Not to mention the countless other ways to be checkmated. Kind of sounds like one of those television series of “1000 terrible ways to die.”

We’ve looked before at code for making the king move, but now we want to break down how we check if the king is safe. Here’s the kingSafe commit, and we can reference several things from that code as we try to understand what I set out to accomplish.

First, let’s take a look back at the flow chart for determining available moves:

  • For each piece, check for valid moves that they can make, where the spaces are empty, or where they attack an opponent’s piece.
  • Add that move to the temporary list.
  • Once we have a temporary list of valid moves, try each move, 1 at a time, and check if the king is safe.
  • If the king is safe, add that move to the “available moves” list.
  • Put the piece back, and try the other moves on the temporary list.

With that in mind, up until now, our engine has not actually checked if the king is safe. We had a isKingSafe() method that always returned true, or “yes, he is”. Now we need to flesh that out and have it really check if it is safe. For the most part, we can combine all the pieces move options into one for the king, and just ask what pieces are at the “end” of those move lines. Here’s the flow chart:

  • Start with the king’s space number, and get the row/column number as well.
  • Using the bishop’s move table, check the next diagonal space until it is not empty. If it is not empty, is it either a bishop or a queen? Then the king is not safe.
  • Using the rook’s move table, check the up/down/left/right spaces until they are not empty. If it is not empty, is it either a rook or a queen? Then the king is not safe.
  • Using the knight’s move table, check the eight “L” spaces to see if they are empty. If it is not empty, is it either a knight? Then the king is not safe.
  • Using the king’s move table, check the surrounding spaces until it is not empty. If it is not empty, is it a king? Or in two cases, a pawn? Then the king is not safe.
  • The king must be safe!

As you can see from the flow chart, it is checking to see if the king is “not safe”. At any juncture that the king is not safe, the rest of the checks are ignored, and a “false” boolean is returned from the isKingSafe0 method. If there are no returns of “false”, then the method returns “true”, for the king must be safe.

In my mind, there are three main ways to handle the king safe issue:

  1. After each piece is moved, have it flag that the king is unsafe (e.g., you check the king, so he is unsafe).
  2. After every move, check from all pieces to see if they are attacking the king.
  3. After every move, check from the king if he is threatened by any pieces.

Method one seems hard to implement, when moving you own piece may illegally threaten the king by no longer “blocking” an attacker. Conversely, method two is way more resource intensive. You would waste time checking both bishops in all directions to see if they “find” the king. Method three seems the most logical, check from the king in all directions for the enemy, rather than from all enemies for the king.

Of the method we chose, there seem to me to be two sub-methods, that of checking if the king is safe, or checking if the king is not. I like to assume the king is safe, unless we find that he is not. I think this is faster, because the moment we find he is not safe, then we quit checking. E.g., if the bishop check reveals the king is not safe, we don’t do the rook, king, knight, pawn checks, we just return “false” – not safe.

Conversely, if we were to assume the king is not safe, and prove he is, we would have to complete all of the checks every time. This would be a waste of resources. Although, with the method I chose, most of the time, the king is safe, so we end up checking them all anyways. But, since we are trying to use this engine on cell phones, we need to save on every resource that we can.

Linux – keep it simple.

Fool’s Mate Friday: Perilous times for pawns!

bp

Did you know that the piece with the lowest survival rate is the white queen’s pawn at d2? That’s right, out of 2.2 million master level games, this pawn survives the least games at only 24.5%. Conversely, king not withstanding, the one piece with the highest survival rate of any of those games is the white king’s rook’s pawn at h2? It survives over 73% of games played! With such a wild spectrum, this small piece is actually the highest and lowest survivor of any chess game. You can check out all of the stats for piece survival here at Oliver’s blog.

Of special interest, Oliver also wrote a program to analyse all of the moves to find that information, which you can look at on GitHub.

Personally, I find the pawn to be the most important piece of the game. But that is for another time. For now, we need to make some pawn moves. Surprisingly, for such a simple piece, it has the most complicated moves:

  1. Pawns can move forward one space.
  2. Pawns can move forward two spaces from the “home” row.
  3. Pawns can attack diagonally forward.
  4. Pawns can perform en passant only under the right conditions.
  5. Pawns can promote to another piece.

I am sure that you realized those moves exist, but by seeing them put to paper we can really get the feel for how complicated making the pawn move is! Of all of those moves, 4 of the 5 are conditional, meaning they can only be done under certain conditions. This makes programming them tough, as you have to check if those conditions exist, then check if making the move is possible, then check if that move is safe for the king.

As you can see in my pawn commit, I added the pawn moves, but there are some flaws in them. Unfortunately, most of these flaws were not realized at the time, but were fixed later, here and here. Essentially, the move that was flawed is en passant, both in the making and the undoing of that move. However, I did not realize it at this point, until I started making the engine perform and undo moves.

So, take a look at the code, and feel free to comment if you think of a better way to do those moves.

Linux – keep it simple.

Fool’s Mate Friday: Keeping the King on the move!

wk

When it comes to king moves, the most interesting is castling, for which I did manage to find a few statistics on the web, based on official games:

  1. White castles kings side 80.2% of the time.
  2. White castles queens side 8.8% of the time.
  3. White doesn’t castle at all…11% of the time.
  4. White castles queens side about twice as much as black.
  5. Castling kings side gives a higher statistic of draws.

From a tactical standpoint, they say that to castle opposite of your opponent creates a more tactical game, while to castle the same side as your opponent creates a positional game. Now I just need to go look up what that means….

In any event, we need to get a move on! Well, at least our king does. So, I created two commits: the king moves, and the king castle moves.

The king moves are really straight forward. I keep thinking that there must be an easier way to do this, but again, it’s just pure math. king position +/- 8 to go up/down a rank, +/- 1 to go side to side, and +/- 7 or +/- 9 to jog diagonally. The easy thing about the king is that he can only move one space… unless he castles.

Castling is rather tricky from a programming standpoint. There are several conditions which must be met:

  • The king cannot be in check.
  • No square the king moves to can be in check.
  • No square the king moves across can be in check.
  • There must be empty spaces between the king and the rook.
  • The king must never have moved.
  • The rook must never have moved.

As you can see, that maneuver alone takes 6 factors into account! Later, I ended up changing this a little bit, rather than booleans of true/false for king moved or rook moved, I went with numbers, but I’ll touch on that later. For now, I went with booleans.

The “king is safe” method has actually not been written yet, so it was interesting to check if the king is safe for this move, before having a way to check that, but in theory it works just fine, once I write the king is safe method. For now, I assign a number to the king’s position, and have it check if the king is safe by moving the number, rather than the actual king, on the logical board, and check if the king would be safe there.

It’s a little complicated, but I think it will do the trick. Be sure to check out the code!

Linux – keep it simple.