Fool’s Mate Friday: Bobby Fischer Teaches Chess

While looking at a few old chess programs for some ideas about my current programming lull, I stumbled across a rather useful old DOS program: Bobby Fischer Teaches Chess. Of course, I knew it originally was a book, but I did not know that it was later turned into a chess program.

The interface is a bit clunky, running in DosBox. Of note, the taller pieces, like queens or kings, often obscure smaller pieces like pawns, due to the board orientation. You might also have noticed that the first pic is our infamous Fool’s Mate! (I just couldn’t help but include it here!)

I went through the first chapter, 1 of 6. If you want to try it out, be prepared for long chapters! It appears to save bookmarks, so I suppose that you could come back to it later.

One thought that this gave me was that of using the JustChessEngine or JustChess interface for instructional purposes…. Perhaps some sort of “find the mate”, or “defend from mate”. Not sure, but it is an idea. I’ll have to think on it.

Linux – keep it simple.

Advertisements

Fool’s Mate Friday: Where to, Governor?

Today’s update is pretty basic. Just cleaning up and filling in some blanks on my JustChess app. While I wont bore you with the whole commit, you are welcome to check it out.

jc9

Basically, I just added an about and settings page. Both pages are pretty basic, but the settings page does have a cool star strength indicator for the computer engine strength. I thought it wise to add it so people could play against the JustChessEngine at lower strengths. It seems a bit funny, since it is currently so weak that I doubt this would be needed. However, it seemed to me, that when making a full fledged app of this sort, one would include some sort of slider or adjustment for the engine strength, so there it is.

This does beg the question of where to go next. As is, my goal was to learn more app making skills and increase my java strength by creating a chess app in which I made my own engine, and one that you could play against a person or a computer. To God be the glory, this app has met that goal. With pass’n’play mode, you could play a friend in a room, or with single player, you can play as black or white against your phone.

But the road forks here.

On the one hand, I could pursue the avenue of making the game playable with someone who was not in the same room, via email, text, online server (parse comes to mind, as I set one of those up for a different app). On the other hand, I could focus on the engine and try to make it stronger.

And yet the road forks again….

One of the big problems is that of programming language. As I delve deeper and deeper into java, I have found only one place that it is applicable, Android. As I’m sure you have seen from my blog, I’ve switched to using Ubuntu Touch on my phone. But Ubuntu Touch doesn’t support java naively (or perhaps at all). As I continue to apply time to learning java, I continue to limit myself to just one application. Perhaps it would be better to learn c++, java-script, or some other language that has a broader application?

So, I sit at the cross roads. What to do next? Hopefully I can figure it out before the next Fool’s Mate Friday!

Linux – keep it simple.

Fool’s Mate Friday: Check or Stale Mate?

Apparently, in 1988, World Champion Gary Kasparov accidentally stalemated his opponent during a blitz tournament in Canada. Mr. Kasparov had a king, queen, and a bishop against Kiril Dimitrov Georgiev’s lone king. The problem Mr. Kasparov was facing was that of time running out. In his efforts to move quicker, he forced a stalemate when he had every advantage and reason to win!

I will probably never be as great as Mr. Kasparov, so I certainly mean no disrespect when bringing this up. My point being is that even world champions can stalemate. How does this apply to my JustChess app? Well, it seems to me that it is pretty important to clarify when the opponent can’t move, if they are in stalemate, or checkmate.

Fortunately, I figured out how to do just that.

jc8

The code wasn’t particularly grueling, it turned out the hard part was figuring out the order of play for pass and play verses playing against the computer. The time which you need to look for a checkmate or stalemate actually changes between those two. Here’s the important snippet, but as always, you can check it out on my GitHub.

    moveOptions="";
    if (!wTurn){
        moveOptions= terminal("suggestMove,black");
    } else {
        moveOptions= terminal("suggestMove,white");
    }
    if (moveOptions.isEmpty()) {
        staleOrCheckMate();
    }

} // End clicked piece.

public void staleOrCheckMate() {
    String status = terminal("checkmate");
    if (status.equalsIgnoreCase("1")) {
        status = "checkmate!";
    } else {
        status = "stalemate!";
    }
    String turnIs = "";
    if (wTurn) {turnIs="White is in ";} else {turnIs="Black is in ";}
    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle(turnIs + status)
            .setMessage(
                    "Would you like to play a new game?")
            .setPositiveButton("View Board", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    // Do nothing.

                }
            })
            .setNegativeButton("New Game", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    // First you define it.
                    Intent myintent = new Intent(MainActivity.this, IntroActivity.class);
                    myintent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    // Now you call it.
                    startActivity(myintent);

                }
            })
            .show(); // Make sure you show your popup or it wont work very well!

}

The longest part of this project was actually testing it against the computer! It’s easy to checkmate it right now, but I found it was a pesky bugger to stalemate! Be sure to give it a try, my GitHub has all of the updates of the app already built for you to download and test out!

Linux – keep it simple.

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: That move was the highlight of the game!

There were several computer GUI systems invented already, but the first (to the best of my knowledge, correct me if I’m wrong) computer GUI that would highlight your move options after selecting a piece was that of “Daly CP”. It was a computer chess interface written for the IDIIOM CAD computer, which was a computer that had a stencil and was used for Computer Aided Design of parts in manufacturing processes. The program was written by Chris Daly, who worked for NASA, and it was used for several tournaments against other computers, as well as against people.

I wanted my JustChess game to highlight the available moves of any piece that you tapped on, similar to what you see in the Daly CP program. Now, every time that you tap on a piece, it’s legal moves are highlighted for the user. This works for both your pieces, and that of your opponent. The process is simple to implement, but lengthy in explaining it here. The whole commit can be viewed on my GitHub, though.

The key problem that I ran into was that of castle moves. The way I was working this was to discern from a query of possible moves for a piece, all of the “to” positions, and to simply change the background color of those tiles. However, castle moves are “k0-0-0”, and “K-0-0R”, etc., as opposed to a standard move, which looked like “P0816*” (Pawn from square 8 to square 16, which is empty – *), from which I was just stealing the 3 and 4 character (remember, computers count the first character as a 0), and parsing an integer. That integer was then used to change the background tile of the corresponding number on the board.

To solve this I used a little trickery with an if/then statement inside of a try/catch block. Essentially saying, “try this: if it is one of these king castle moves on the list, then highlight x square, if not, then use the normal method.” It seems to have worked quite well. The great thing is, you can test it out for yourself now! That’s right, I’m releasing JustChess, version 1.0 for download. So give it a try and let me know what you think!

Do keep in mind, it has a long way to go, but is currently completely playable against the phone, or in pass and play two player mode.

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: 8 minute moves….

2-1.Bernstein-alex.1958.L02645391.IBM_ARCHIVES.lg

They say that the first complete chess playing program was written by Alex Bernstein in 1957. There were earlier renditions that could not play a complete game, but could solve tactics puzzles or make move suggestions, however, the Bernstein Chess Program was the first computer program that could actually completely evaluate and play a game of chess. For grins, I looked it up, and it was played on an IBM 704 computer, which was an entire room. It took about 8 minutes to make each move, before printing out the board on a piece of paper. You can check out a video of him playing the machine on YouTube.

My JustChess game is not so glamorous, but it is getting more interesting with each passing reiteration as I work on it’s programming. Last week, I talked about how you can now actually play against the phone/computer or against a person in pass and play mode. There were several bugs that still needed to be ironed out. In particular, making a move by the computer sometimes erroneously rearranged pieces on the board.

I found a quick and dirty work around for that. What I changed in this latest commit was that of how moves are made. What appears to be happening, as the ply goes up, the phone runs into a problem where the threads of various potential board positions are getting moved or mixed up. Probably due to poor code on my part. Either way, it then makes moves on boards that were not the actual play board, but that were hypothetical boards and pieces moved during it’s multi-ply search. I think.

So, to avoid this problem, I have changed the order of things, and added a step to copy down the board as it is, before a move is calculated, and then use that copy of the board to make the move with. Here’s a breakdown:

  1. Write down a copy of the board, as it is.
  2. Calculate the multi-ply best move with the original board.
  3. Write down the best move.
  4. Re-write the original board with the backed up copy, just in case it got messed up.
  5. Make the best move that it wrote down.

This seemed to work pretty well, most of the time. It completely fixed the issue of messed up or mixed up board pieces. However, it now has another new problem, where it can occasionally get “stuck”, and the program will hang until it is closed by Android. This seems to happen randomly, and doesn’t happen every game. So, more work to be done for sure.

I’ve also been “tuning” the JustChessEngine as well. But that’s another post….

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: Pawn Promotion Possibilities!

Back in the middle ages, there were several different renditions of pawn promotion. Originally, the pawn would promote to the queen piece, but back then the queen could only move one space, like the king. Then there was the rule that the pawn could promote only to a captured piece. So if there were no captured pieces, the pawn would sit there on the end row until one was captured, which would immediately replace the pawn.

Perhaps the most interesting rule, though, was that of the pawn being promoted to the piece on which it’s rank was. E.g, the queen’s bishop’s pawn (c2) would promote to a bishop, a knights pawn a knight, and a king or queens pawn, to that of a queen. This would definitely change the face of a chess match as we know it!

The two player functionality of my chess app, in pass and play mode, is getting closer and closer to completion! Today I had a few minutes and I still had several obstacles to fix, so I decided to tackle one of them.

if (myMove.contains("P48")||myMove.contains("P49")||myMove.contains("P50")||
        myMove.contains("P51")||myMove.contains("P52")||myMove.contains("P53")||
        myMove.contains("P54")||myMove.contains("P55")) {
    if ( minusNum == 8) {
        myMove = "Pu" + promoteToW + played + String.valueOf(theBoard[number]);
    } else if (minusNum == 9) {
        myMove = "Pr" + promoteToW + played + String.valueOf(theBoard[number]);
    } else if (minusNum == 7) {
        myMove = "Pl" + promoteToW + played + String.valueOf(theBoard[number]);
    }
}

if (myMove.contains("p08")||myMove.contains("p09")||myMove.contains("p10")||
        myMove.contains("p11")||myMove.contains("p12")||myMove.contains("p13")||
        myMove.contains("p14")||myMove.contains("p15")) {
    if ( plusNum == 8) {
        myMove = "pu" + getPromoteToB + played + String.valueOf(theBoard[number]);
    } else if (plusNum == 7) {
        myMove = "pr" + getPromoteToB + played + String.valueOf(theBoard[number]);
    } else if (plusNum == 9) {
        myMove = "pl" + getPromoteToB + played + String.valueOf(theBoard[number]);
    }
}

pawn_promote

Essentially, I just added a check to see if it was a pawn promotion when you choose what you are trying to do. Fortunately, there is only one row for black, and one row for white where this maneuver can be done. Be sure to check out the commit for the comparison of the changes.

Linux – keep it simple.

Fool’s Mate Friday: Castle, anyone?

From the git-go, one of the hardest parts of making this chess engine and the following gui system has always been the pawns and the king. Both of these pieces have unusual maneuvers that you can’t easily explain with the traditional shorthand that I was using for the engine. Things like castling, en passant, and promotions.

If you recall last time, I made the pieces movable with a simple two touch interface. The problem is, it checks against the engine to see if that is a legitimate move in the form of piece+square from+square to+captured. This works great for queens and bishops, rooks or knights, but doesn’t bode well when someone tries to castle. This brought me to a fork in the road: change my engine, or manipulate my gui.

I think I should have changed my engine, but I already re-wrote it from scratch, twice. I just don’t have the time to do that again. So, I went with the easier/quicker/less skilled method of manipulating the gui.

Here’s the commit:

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);

        if (myMove.equalsIgnoreCase("K0406*")){myMove="K-0-0R";}
        else if (myMove.equalsIgnoreCase("K0402*")){myMove="K0-0-0";}
        else if (myMove.equalsIgnoreCase("k6062*")){myMove="k-0-0r";}
        else if (myMove.equalsIgnoreCase("k6058*")){myMove="k0-0-0";}
        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.

Essentially, I know there are only 4 possible ways for a king to castle, so I make the gui check to see if that is the case, and then pass the correct move verbiage to the engine. Pretty slick trick for the moment, but it may fall short for en passant. I’ll have to check on that…

Linux – keep it simple.