Sprite Fun: updated!

Since my previous post, the official development environment for Android changed from Eclipse (with a plugin) to Android Studio. The Sprite Fun game I made still works — if anything maybe it’s a little simpler.

The instructions are as follows:

  • Download and install Android Studio
  • Create a new project with type “Empty Activity” (the default)
  • In the src folder, replace the MainActivity.java with the MainActivity.java from this example, and add the two other classes from this example in the same package (changing the package name to match the package name you chose when creating the project).
  • Add the default green Android icon as an image that the app can use:
    • Select File > New > Image Asset
    • In the wizard, select “Asset Type” > “Image” and change the name to “greeny”
    • click “next” and then “finish”.

Then you’ll have a fun app that’s very simple to understand and extend — to help kids teach themselves real application programming in a real development environment!

Here are the java source code files for this example: SpriteFun2.zip

Have fun!

Beginner programming example for kids with Android!

A little background:

My dad taught me some basic programming back in the 70’s when I was 8 or 9 years old.  And when I say basic, I mean really basic Basic — entirely text-based, using “goto” to go to different line numbers in the program for control logic, etc.  But it was the first I’d ever seen of being able to program a machine to respond to input.  So even making a simple text-based game like “Guess the animal” was amazing and fun!

Now my kids are 11 & 12 years old, and certainly capable of learning to program.  But the problem is that programming “Guess the animal” isn’t interesting at all when you’re used to games like Angry Birds and Plants vs. Zombies.  (It’s a little like how my dad tried to get me interested in building the circuitry of a radio — which was so cool when he was a kid! — but was too old-fashioned to be interesting to kids of my generation.)

So I’ve spent a lot of time trying to find some programming project that is simple enough for beginners, yet cool enough to keep my kids’ interest.  And I’ve found it: Android, with my simple example program “Sprite Fun”.

This example is not intended to illustrate any kind of “best practices” for Android programming.  It’s optimized to be simple enough that even someone who doesn’t know much (if anything) about programming can understand how it works (and modify it), while having the coolness factor of “Hey I made a real app that I can play on my phone!” — to help kids get excited about teaching themselves to program.

The person setting it up doesn’t really need to know anything about Android programming either except for some basic familiarity with Java and Eclipse.  The first step, naturally, is to download and install the Android SDK, and launch the Eclipse installation that is bundled with it (see here). Then go through the “new Android Application Project” wizard, selecting all of the defaults (and giving it your own package name — I called my project “SpriteFun” and used my domain org.outerblogness).

In the initial version of the SpriteFun game, all it does is allow you to create little androids and move them around by touching the screen.  If there’s no android in the spot you touch, it creates one, and if you select one with your finger, you can move it around by moving your finger around the screen.

All you have to do is add a segment to the default MainActivity class (to set the view), and then add two new classes “SpriteFunGameView” and “Sprite”.  Here’s what to add to MainActivity.java (replacing the default “onCreate” method):

    private SpriteFunGameView mSFGView;


    // the list of Sprites to display:

    // static to save them when the orientation changes:

private static List<Sprite> sprites = new LinkedList<Sprite>();



    protected void onCreate(Bundle savedInstanceState) {


        Log.v(“”, “in SpriteFun”);

        // Create a SpriteFunGameView instance and set it

        // as the ContentView for this Activity.

        mSFGView = new SpriteFunGameView(this, sprites);



And here’s the SpriteFunGameView.java class:

package org.outerblogness.spritefun;


import java.util.LinkedList;

import java.util.List;


import android.content.Context;

import android.graphics.Canvas;

import android.util.Log;

import android.view.MotionEvent;

import android.view.View;


public class SpriteFunGameView extends View {


Context context;

Sprite activeSprite;


List<Sprite> sprites = new LinkedList<Sprite>();


// canvas boundaries:




    public SpriteFunGameView(Context context, List<Sprite> sprites) {


        this.context = context;

        this.sprites = sprites;




   protected void onDraw(Canvas canvas) {


      canvasWidth = getWidth();

      canvasHeight = getHeight();


  for (Sprite sprite : sprites) {






   public boolean onTouchEvent(MotionEvent event) {

  // tell android to repaint the canvas



  // get the location of the touch:

  int xPos = (int)event.getX();

  int yPos = (int)event.getY();


  Log.v(“”, “x: “ + xPos);

  Log.v(“”, “y: “ + yPos);


  int action = event.getAction();

  if (action == MotionEvent.ACTION_DOWN) {

  Log.v(“”, “ACTION_DOWN”);

  activeSprite = null;

  for (Sprite sprite : sprites) {

  if(sprite.isInSprite(xPos, yPos)) {

  activeSprite = sprite;



  if(activeSprite == null) {

  activeSprite = new Sprite(context, xPos, yPos);



  } else {

  Log.v(“”, “not ACTION_DOWN: “ + action);

  if(activeSprite != null) {

  activeSprite.setCenter(xPos, yPos);   







And here’s the Sprite.java class: 

package org.outerblogness.spritefun;


import android.content.Context;

import android.content.res.Resources;

import android.graphics.Canvas;

import android.graphics.drawable.Drawable;

import android.util.Log;


public class Sprite {


Drawable myImage;


// image bounding rectangle:






public Sprite(Context context, int x, int y) {

        Resources res = context.getResources();

        myImage = res.getDrawable(R.drawable.greeny);

        setCenter(x, y);

        //imageWidth = myImage.getIntrinsicWidth();

        //imageHeight = myImage.getIntrinsicHeight();

        imageWidth = 144;

        imageHeight = 144;



protected boolean isInSprite(int x, int y) {

if(x < imageX) return false;

if(x > imageX + imageWidth) return false;

if(y < imageY) return false;

if(y > imageY + imageHeight) return false;

return true;



protected void draw(Canvas canvas) {

        myImage.setBounds(imageX, imageY, imageX + imageWidth,    imageY + imageHeight);




protected void setTopLeftCorner(int x, int y) {

imageX = x;

imageY = y;



protected void setCenter(int x, int y) {

imageX = x – (imageWidth/2);

imageY = y – (imageHeight/2);



And in the “res” folder in the project hierarchy in the left sidebar, create a new folder called “drawable”, copy into it the icon from one of the other “drawable” folders, and rename the copied image “greeny.png”.  For this first game, you don’t even need to create your own image — just use the default icon as the game character image.

My kids were immediately excited about the game and about making modifications!  They came up with lots of ideas of new features to add.  For example, they wanted an eraser that could be used to erase the androids, and they googled around and found a bunch of additional android icons of different colors to use, and requested a row of buttons to select the color.

Touch-screen programming is great for people who are just learning, because it’s conceptually very easy to use the coordinates of the user’s finger. It’s so much easier than old-fashioned keyboard-based navigation where you need a whole framework to navigate around selectable widgets and decide which one is highlighted, etc.  It was very easy to add a button implementation the kids could understand just by drawing the button on the screen and checking whether the touch event is in the button!

Here you can download the complete project (with the buttons and eraser): SpriteFun.zip

Note that each Android project has an additional “appcompat” project that is added by default (and needed by the program) — which I did not include in my zip file linked above. So I don’t think you can simply import my example.  Just create your own with the “new Android Application Project” with the wizard, and copy-paste the contents of the three classes into Java classes you create with the menu, and copy-paste the images from the res/drawable folder into your own res/drawable folder.

The project was a big success!  My kids started making their own modifications and their own games. After playing with this for a bit, my older son even went back and spontaneously made a new program with Scratch (which my kids had played with for a bit, but had gotten bored of).  And he’s working on a new update to his own mini version of “Plants vs. Zombies” right now!

Minecraft Server automated backups and automatic restart (Linux)

I like to run my Minecraft server from a cron job so that I can have a script check once a minute if it’s running (and restart if if necessary, without any manual intervention).  But that makes it very tricky to send commands to the server console to automate the backup.  What to do?

A colleague of mine suggested using the “screen” command (here’s an example of using screen to automate Minecraft backups), but I hit upon another solution that I like better: I use a simple script to read commands from a file and echo them, and I launch the Minecraft server by piping my command reader script to it.

Here’s the script I run as a cron job to keep my Minecraft server running:

# check if the server is running and store that info in a variable:
RUNNING=`ps -ef | grep minecraft_server | grep -v grep`
cd /home/myusername/minecraft_server_folder
if [ -n "$RUNNING" ]; then
# log the fact that it is running:
date > running.txt
# relaunch sequence
# stop the command reader:
echo stop > cmdfile
# give the command reader time to stop:
sleep 10
# clear the command file, in case the command reader wasn't running:
truncate --size 0 cmdfile
# log the restart and try again:
date > restart.txt
/home/myusername/bin/commandReader.sh world | ./launchserver.sh

I save that script in my bin folder as keepMinecraftRunning.sh and add this line to my crontab (using crontab -e):

* * * * * /home/myusername/bin/keepMinecraftRunning.sh

And here’s the commandReader.sh script that sends commands to the Minecraft server:

# set what time to make the backup:
# make sure the command file exists:
touch cmdfile
while [ "$COMMAND" != "$STOP_CMD" ] ;
COMMAND=`cat cmdfile`
if [ -n "$COMMAND" ]; then
truncate --size 0 cmdfile ;
echo $COMMAND ;
# wait a few seconds before reading the command file again:
sleep 5 ;
# if it's backup time, make the backup:
CURR_TIME=`date +%H%M` ;
if [ "$CURR_TIME" = "$BACKUP_TIME" ] ; then
echo save-all ;
echo save-off ;
CURR_DATE=`date +%Y%m%d` ;
# $1 is the argument, which should be the name of your world (eg. "world")
# This makes a daily tar of your world, in a file like world_20121021.tar
tar cf $1_$CURR_DATE.tar $1 ;
echo save-on ;
# wait a minute to avoid saving twice:
sleep 60 ;
sleep 1

I save this script in my bin as commandReader.sh.  Aside from making the backup, the script simply reads whatever is in the file “cmdfile” (created in the minecraft server directory), pipes the command to the minecraft server, and clears the file.  So if I open any terminal on the machine running the server, I can simply send commands to my Minecraft server like so:

echo "time set 0" > /home/myusername/minecraft_server_folder/cmdfile

And echoing “stop” into the file stops both the Minecraft server and the command reader script.

In my minecraft server folder, I put a script called launchserver.sh. This can be just the standard launch command line (java -Xmx1024M -Xms1024M -jar minecraft_server.jar nogui), but I found the server performs better if I use a script that calculates the appropriate amount of memory — see the script here.

Then — with the server taking care of itself — I can get back to the important business of building castles!

Minecraft: Why Lego Group are kicking themselves about now…

I’m usually more interested in implementing video games than in anaylzing video game design, but I think the success of Minecraft alongside the failure of Lego Universe provide a really interesting example.

First of all, I love Legos — they’ve been my favorite toy forever — and I have two little boys (ages 10 and 9) who also love Legos.  Last year, when Lego first announced Lego Universe, I looked forward to trying it out.  I figured that my kids were about the age where they’d be wanting to play online multiplayer video games soon, and rather than fight it, I might as well steer them towards more interesting ones.  So we signed up for the free version, and played it a bit.  It wasn’t addictive, but I didn’t expect it to be.  I figured I’d probably sign up for the paid version at some point, but never quite got around to it.

Then one day my younger son was watching Lego videos on YouTube, and YouTube’s sidebar of related videos turned up a Minecraft video.  My son watched it and was hooked.  He spent so much time watching YouTube videos of people playing Minecraft that my husband figured it was ridiculous for him to watch the game so much and not play it, so he bought him a Minecraft account.  And after watching my son play this game just a little, I knew I had to get myself an account, and one for my other son.  And we have had a fantastic time playing together!!  Here’s a video we made of us playing attack/defend the tower:

Right off the bat, I became wildly hooked on this game!  It’s really unlike me, too, because I don’t normally play video games all that much — I certainly don’t generally spend hours on end playing a video game!  But it hit me that a lot of what makes this game so much fun is kind of the same thing that makes it so much fun to play with Legos.  Watch this video I made about strategies for constructing a defensive fortress, and see if you see what I mean:

Basically, you have the raw materials to build whatever you want, and the game is totally open-ended about what your objectives are.  If you want to build the most amazing building/city/castle, you can.  If you want to go around fighting monsters, you can — and you can figure out and build tricky traps for them if you like (but you don’t have to).  If you want to go on a scripted, pre-set adventure, you can.  Just go to YouTube and look for different Minecraft challenges — you can download different obstacle courses and adventure maps that other people have constructed.  What’s more, if you want to script/construct an adventure for other people to play, you can!  Just upload a video of it to YouTube when it’s done.  (Minecraft makes it fun for users to share content.)

This is part of the same reason why Lego toys have such universal appeal.  My kids like the story of the Ninjago universe, for example, and play stories of the characters that Lego invented for them.  However, if you’d rather just use your own ideas to build something, you can.  Here’s a tree-house I built a while ago:

The biggest additional appealing element that Minecraft has (but Lego doesn’t) is the three-dimensional environment made of blocks.  Since virtual blocks are free, why not?  And Minecraft has a really good algorithm for generating interesting landscapes and cave systems.  I’ve found it’s actually kind of fun to simply wander around and explore the randomly-generated world.  Another fun thing is that you have the choice of setting it to “creative mode” — where you can have an infinite number of any brick or item you need — or to “survival mode”, where there’s a bit of challenge involved in finding or making the blocks and items you want.

Playing the video game that got it right made it crystal clear what Lego Universe did wrong.  In a nutshell, Lego Universe was way too scripted.

I watched/helped my son play Lego Universe, and we were given a set scene and a long series of trivial tasks to perform in order to advance through the game.  The worst part was that they scripted what your character needs to “build”.  I put “build” in quotes here, because, really, you just press a button and your mini-figure waves its little arms, and the item you need to build in this part of the script just appears.  (I understand that the paid version was more open-ended, but I never saw it because we were kind of turned off by the free part.)  Contrast this with Minecraft, where — using a handful of mechanical/electrical pieces — people build all sorts of different machines, from simple vending machines to entire, functioning computers!  There are simple formulas you can build if you want to (like golems), but mostly the raw materials are pretty simple and open to possibilities.

When Lego Universe first shut down, they posted a video explaining what had happened.  I think they’ve since taken it down (because I can’t find it anymore), but the striking part was that they’d started out with a more open-ended game, and did some focus groups, and some twelve or thirteen year old kids told them they’d rather have a more scripted game.  So Lego came up with a rather generic evil universe storyline — of the same variety that every toy company uses to sell toys to boys ages five to fifteen.  This shows the danger of trying to use focus groups for the original ideas of your product.  Obviously twelve-year-old kids are going to tell you to just copy some other games that they like.

Normally this sort of story wouldn’t be surprising at all:  a clever individual comes up with a brilliant idea that that giant, bureaucratic corporation couldn’t/didn’t think of.  It just surprised me because Lego Group has generally done a very good job of staying ahead of the game in terms of good ideas.  The Ninjago series is more interesting and fun than similar, competing toy lines like Bakugan and Beyblade.  The surprise mini-figure packs at the toy store checkout counter are a fun impulse item — and something that other toy companies have since copied.  They have a good mix of theme construction sets (like Star Wars and Harry Potter) along with sets that start you making your own story, like City and Castle.  They have a huge number of simple pieces, and you can use the ideas from the sets to make interesting things out of them, or come up with your own construction ideas.  Even their Advent Calendar had a bunch of clever ideas for making interesting items out of simple raw materials.  Plus, they figured out that a good part of their customer base is actually adults — and they came up with a series of sets that are marketed to adults, like the elaborate London Tower Bridge.

In twenty-twenty hindsight, I think Lego’s biggest error was to leave too much of the planning of Lego Universe to their (very successful) video game department, instead of leveraging what people like about Lego toys.  The video game department is successful largely because people love Lego’s iconic mini-figures, which make a fantastically easy-to-animate set of characters for video games.  That’s great, but something that’s “Lego Universe” should feature more of Lego’s universal appeal.  Since they intended their video game to be for kids and teens on the young end of online multi-player gaming, they were foolish not to take advantage of the fact that the parents (the ones with the wallets) often enjoy playing Legos with their kids — and make a game that’s fun for parents who like to build things.

I imagine that Lego will come out with a copycat game.  They would be foolish not to.  But I hope they get their ideas team in gear and add something really new to it themselves, and don’t just make a pale imitation of Minecraft.

Experimenting with BlackBerry Graphics!

As I said the other day, I started my space explorer game by trying out a bunch of different ways to animate the rocketship flying through space.  (I’ve bundled all the source code and resources for the complete example — you can download it here.)  I started by just creating a standard MIDlet using the javax.microedition.lcdui.game classes.  Here’s what it looks like in the debugger:

In the image, I’ve set the debugger to show memory usage.  In this case it’s “lcduispace” — the top process on the list.  Next, I decided to try out the technique I described in my earlier post:  use the same lcdui game implementation, but write each frame into an image buffer and transfer it from the MIDP Graphics implementation to RIM’s proprietary implementation to display it in a RIMlet.  Here it is in the debugger: Read more »

BlackBerry on JavaRanch!

At JavaRanch (a friendly place for Java greenhorns), they’ve just added a new BlackBerry forum!  And as an opening event, they’re doing a promotion where you can win a copy of my book Learn BlackBerry Games Development.  As part of the promo, I’m answering questions there this week.  See you there!😀

BlackBerry’s two Graphics implementations: Can you use them both? In the same App?

When I first started programming for BlackBerry, one of the things that struck me as most odd was the two completely independent graphics APIs.  For MIDlets, there’s javax.microedition.lcdui.Graphics, and for RIM’s own profile, there’s net.rim.device.api.ui.Graphics.  The two versions are so similar to one another that — if you’re careful — you can write a game that can use either of the two graphics APIs interchangeably, just by swapping out the include statements (and using a different set of lifecycle classes).  That’s what I illustrated in Chapter 3 of my book.

But I wondered: What if I want to use the javax.microedition.lcdui.game package?  But I still want to take advantage of RIM’s proprietary UI component handling?  Is that even possible?  Note that you can’t just place an LCDUI Sprite onto a RIM Screen or use lcdui Images interchangeably with RIM Images.  Yet, there’s nothing to stop you from instantiating many of the lcdui graphics-related classes in a RIMlet — either type of application has access to the whole API.

Through experimentation, I found that it’s quite possible to take a game that was written using lcdui game Layers and run it in a RIMlet.  The trick is the following: Read more »

QA & Dyslexia

I’ve got some BlackBerry posts coming up, but first I’d like to say a few words about why I haven’t posted anything in six months.  There are two reasons:

  1. I don’t like Windows OS.  I’ll use it if I have to, but for my dev environment at home, I was just too tempted to clean the hard drive (once I’d finished my BlackBerry book), and replace the OS with Linux.  Naturally, I told myself I’d set my BlackBerry dev environment back up on some other machine or in a virtual machine or something, and — since I love installing Windows so much — you can imagine that that task hasn’t come to the top of my “to do” list.
  2. I’m excited about my current job, and it’s something completely different: QA engineering for Dybuster.

Dybuster is a software suite that helps dyslexic kids learn to read.  For the kids it’s a game.  It works by giving the kids additional ways to learn words, using colors, tones, and 3D graphical representations:

Dyslexia treatment software by Dybuster

Since I’ve been testing it, I can say that it has definitely improved my spelling in German.  Of course I’m not Dyslexic.😉

And, fortunately, there’s an English version available too (including a free downloadable demo version).

Learn BlackBerry Games Development!!!

So, my new book — written with co-author Andrew Davison — is done and ready to go!

Have a look at the book’s website to get an idea of what you’ll see:

  • Chapter 1. Gaming on BlackBerry!
  • Chapter 2. BlackBerry Application Basics
    Why are there two types of BlackBerry Java applications? What are all those crazy files the compiler generated? And – most importantly – how do I get an application complied and running on my BlackBerry smartphone? Chapter 2 will answer all of these questions, plus help you set up a professional build with Ant.
  • Chapter 3. Game Graphics and Events with MIDP and RIM Classes
    Using the classic Maze game as an example, you’ll see exactly how the two types of BlackBerry Java applications differ. You get an in-depth look at how the lifecycle, events, and graphics work in both cases so you’ll be ready to develop whichever kind is best suited to your game’s needs.
  • Chapter 4. Adding a Professional Look and Feel
    Gorgeous graphics are critical for the game experience. To get your game’s visual theme pixel-perfect on every model, BlackBerry gives you the tools, and Chapter 4 explains how to use them.
  • Chapter 5. Security and Selling Your Game
    As much as you love games for their own sake, at the end of the day it’s nice to get paid. In Chapter 5 you’ll see how to sell your game on BlackBerry App World (or on your own site) – plus how to apply the cryptography APIs to implement licensing and Digital Rights Management.
  • Chapter 6. Swingin’ Light Saber
    With action, music, sound-effects, colliding game sprites, and even touch-screen input, Andrew shows you how to put it all together and develop a real game. Plus BlackBerry’s accelerometer lets you wield your saber like a true RIM-i Knight!
  • Chapter 7. Play a Live Opponent with SMS
    That classic, tiny packet of data sent by the Short Message Service is still a favorite with users and operators alike. And it’s all you need to play a trans-atlantic game of Checkers with a friend – chosen from your BlackBerry contact list!
  • Chapter 8. Using Scalable Vector Graphics
    2-D graphics are easy to master and allow you to create surprisingly impressive effects. Check out Chapter 8’s spinning spaceship video and learn the tricks to create it.
  • Chapter 9. Creating Role-Playing Games on the Internet
    Since Internet everywhere is BlackBerry’s strong point, it was practically born for Massively Multiplayer Online Role-Playing Games (MMORPGs)! Chapter 9 uses Twitter to create a virtual asteroid belt that you can explore and find real people in their own virtual ships.
  • Chapter 10. Remotely Drive a (toy) Sports Car
    What’s more fun than driving a remote controlled car? Driving one from your BlackBerry! Andrew illustrates Bluetooth programming in style.
  • Chapter 11. Fox and Hounds
    Here’s something your stationary game console can’t do: a real live game of hot pursuit – based on GPS!
  • Chapter 12. Introducing 3D with JSR 239
    Have a look at what the latest-and-greatest version 5 BlackBerry smartphones can do! Andrew explains 3-D graphics with OpenGL.

Also note: I have some “outtakes” — sample games and code that didn’t quite make it to the book but are nonetheless kind of interesting.  I’ll be posting them here over the next few months.

A basic QTestLib and qExec example (for engineers with experience in Q.A., not Qt!)

When doing a software QA project, you have to be ready to set up and design tests in a variety of different programming (and scripting) languages — to best integrate the automated tests with the rest of the project.  I’ve worked in C/C++, but I’m far from being an expert on the subject. So I can end up wasting time on points that would be extremely simple for an engineer who works in C or C++ every day. And since I wasted my time on this, I’m posting my notes so that you won’t have to do the same.

I recently added some tests to the automated build of a C++ project that uses Qt, which has a built-in unit testing framework: QTestLib. QTestLib seems reasonably well-designed in terms of features. There were just a couple of points I felt were missing from the tutorial, so I’m posting a few remarks for the sake of Q.A. engineers who need to dive straight into the Qt unit test framework. (Apologies in advance to C/C++ developers who will undoubtedly find these points laughably trivial…)

I’m assuming here that you’ve already done at least the first chapter of the tutorial.  If not, go do it now — it’s very short.

Done? OK, let’s get started. My #1 problem with the tutorial is that it explains how to create a stand-alone application that runs a single QTest class, but doesn’t explain how to create an application that will use QExec to run a series of QTest test suites. Like so many things in software engineering, it’s very simple (once you know the trick).  And today I’m going to tell you the trick! Read more »