Game restarts when minimized!

When I originally created JustChess, I had a problem. If you were playing a game, and pressed the new game button, then started another game, you could press back and go back to the menu, then back and go back to the game. This was a bit odd. At the time, I solved it with “Intent.FLAG_ACTIVITY_NO_HISTORY”. This worked great. Too great.

The problem, as pointed out on my issue tracker, was that when you minimized the game, it would be “destroyed” and rebuilt when you brought the app back. Which is not cool. You may need to answer a text and then come back to your game, and it shouldn’t disappear in between!

minimized

So, I fixed it with my latest commit. I took out the FLAG_ACTIVITY_NO_HISTORY intents, but then my original problem returned. To solve that, I added “finish()” to my new game button, like so:

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

}
})

Now, when you select a new game, it “finishes” your old one. Pressing the back button doesn’t lead you on a wild goose chase to dozens of old games, it just brings you back to the main menu, and that’s much better!

Linux – keep it simple.

Advertisements

Can’t play chess in landscape mode!

Another one of the great issues brought up by a user of JustChess, my simple chess playing Android app, was the fact that when the screen was rotated, you can’t see the bottom half of the board!

Realistically, this would require one of two things:

  1. Fixed portrait mode, not allowing the user to rotate the screen.
  2. Having a separate layout that was appropriate for the rotated screen.

But instead I chose option number 3: Add a scroll view!

Option 1 would limit users from being able to hold their phone a different way if it was more comfortable, and that doesn’t solve any problems, it just limits use.

Option 2 is the proper way to fix this, but I’m done working on this app right now, and involved in other project. This would be a bit of an overhaul, and would take me a considerable amount of time.

Option 3, is cheating. I am adding a scroll view so that the user who wants to play in landscape view can scroll the board to recenter it on the screen. This is fine for hi-res screens we see today, but may be a problem on an older phone, where the user would have to scroll the board back and forth to see all of it.

slide

Either way, you can see the full commit on my GitLab, but here is the pertinent part of the code, in the layout xml file:

<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
...... edited for space .......
    </LinearLayout>
</ScrollView>

This neatly wraps everything up into a nested scroll view which the user can move by swiping. This may also help if in portrait mode on an older phone with a very small screen.

Linux – keep it simple.

The game restarts on screen rotation!

After my JustChess app hit the F-Droid repository, I was pleasantly surprised to hear that people were trying it out! With every wave of players, however, came a new wave of issues. I like issues. I’m a bit of a problem solver, so it gives me a clear direction to work towards.

One of the issues was that rotating the screen caused the current game to be destroyed and restarted. Of course! I should have thought about that. Since I sold my Android phones, I was using the emulator to finish building this game. With the emulator, I didn’t consider screen rotation!

Fortunately, the first fix is pretty simple. If your activity restarts on rotation, then you should add this line to your manifest for each activity:

android:configChanges="orientation|screenSize"

Like this:

<activity
    android:name=".MainActivity"
    android:configChanges="orientation|screenSize"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar" />

You can check out the full commit on my GitLab, but that is all you need to fix this issue. Now I just need to make it playable when the screen is rotated!

rotating

Linux – keep it simple.

Fool’s Mate Friday?

Fool’s Mate Friday is going to take a little detour, as I work on learning a new programming language.

If you have followed my blog at all, you will notice that I’ve made a bit of a shift away from Android. When I was working with Android, I was heavily invested in Java programming, both for games and app, as well as making custom ROM’s. I’ve come to realize though, that while Java is cross platform, it is a bit of a niche these days.

Java is used by Android, but rarely used by other computer operating systems. True, it CAN be run on just about any OS, but usually ISN’T. Most browsers have dropped Java applet support, and most OS’s don’t include Java support without installing some form of JRE (Java Runtime Environment).

As I’ve switched (at least temporarily) from Android to Ubuntu Touch (UBPorts), I’ve seen a real need for more robust apps for that platform. Unfortunately, UT doesn’t support Java natively, and that left me out in the dark.

But, God gave us brains, and I’m always trying to use mine to learn new things, or master things I already know. So, I’ve decided to take up a new programming language. Obviously, if you read the title, you already know that I picked C++.

It can be hard to just “learn” something new by reading a book, or looking at code. One of the things that helped me a lot when learning how to make Android games was to sign up for a class on Udemy by Rob Percival. He made the course fun and dynamic by making little creative games or applications to teach the student new concepts or ideas. With that in mind, I jumped back on Udemy and snagged a course (during the $10 site-wide sale) called “Beginning C++ Game Programming“. It focuses on teaching a complete noob how to program in C++ by creating 3 simple games.

One of the perks to this programming style is getting to see something get created from start to finish, and have a graphically playable product when I’m done. It uses the SFML library (which sounds like a dirty acronym, but really is an open source library – Simple and Fast Media Library) for handling the graphics, and it seems to be really intuitive and straightforward. It also seems to be very similar to using libGDX that I was using with Android, so that make working with it easy for me to learn.

Since Java and C++ are both object oriented languages, the concepts of each are the same, which is helping me in the learning process. Although I still try to type things the Java way, so that may take a while to get used to. Either way, I’m having fun with the course, and while I’ve only completed about 15% of the course, it has been interesting and fun.

sfml_timber_1

The course does use Microsoft Visual Studio, however, I’m just using Geany to type and compile my programs. Other than one or two little snags about include files being different from Windows and Linux, I haven’t had any trouble doing things my way. Hopefully you’ll enjoy hearing about the journey!

Linux – keep it simple.

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.

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.