Minimum Distance between a Point and a Line

I haven’t published a blog post in quite a while! Whoops!

I have several in the works, one in particular comparing the JavaScript Engines Nashorn and Rhino that is near completion, and another one on something I’ve been doing with my Raspberry Pi.

For now here’s a short web page I put together showing how to work out the minimum distance between a point and a line based upon a solution posted on this website, which has some very useful formulas for working out problems in 2D and 3D space. I’ve only written an example for the first formula on this page, hopefully seeing it as an interactive visual representation might help anyone struggling with understanding how to find the minimum distance between a point and a line.

You can view the example here: http://lyndonarmitage.com/html/points_and_lines/

I’d suggest viewing it in a web browser that supports the range input type (Opera, Chrome, IE10) as it let’s you adjust the values more easily, although it works just as well in a browser that does not support the range input type yet.

GlassFish + Ant = Bug?

Note: This is a blog post detailing a perceived bug with the GlassFish Application Server. It has nothing to do with Games programming or the Raspberry Pi like the rest of this blog.

Recently at work I’ve been working on a PDF to Android App converter (link there for those interested). The application itself uses one of our already created and well maintained products and is not the focus of this blog post. What is the focus is the issue I ran into when attempting to add the option to our online PDF conversion service that uses Oracle’s GlassFish 3 as the application server behind it.

Our service itself is pretty simple it let’s a user upload their PDF file and the conversion is run on our GlassFish server with the results served back to the user (be they HTML, SVG or some other format). Adding the Android Converter to this mix should have been as simple as adding any other mode, and it was, for the most part.

The problem I ran into was when I attempted get the server to also build the converted file as an Android application, something relatively simple to do as it uses Apache Ant to build the apk file. What happens is I encounter an error to do with the classloader Ant is using that looks like this:

C:\androidsdk\adt-bundle-windows-x86_64\sdk\tools\ant\build.xml:109: taskdef A class needed by class com.android.ant.GetTypeTask cannot be found: javax/xml/xpath/XPathExpressionException
using the classloader AntClassLoader

That’s the relevant part, I shortened it for clarity as there was also the call stack. After struggling with finding a solution for this error for about a week I turned to Stack Overflow in the hopes of finding someone who knows more than I do about class loaders and the problem I am facing. My post can be found here.

I persisted further in my efforts to find a solution (balancing attempting to solve the issue with my other work load), and found that the same code when run using Apache Tomcat worked fine. Case closed some of you might say, switch to Tomcat, except we used Tomcat before at work and had a few problems with it.

So now I am stuck for ideas, so I thought I’d create an example project to see if other people including the GlassFish developers would weigh in on the subject of what the issue could be and whether there’s a coding solution I am not seeing (hopefully there is) or if there is in actuality an issue with GlassFish.

The example can be downloaded here. It contains a Netbeans project with the appropriate code and a basic Android Project with a valid build file.

The example NetBeans project file contains some instructions in it’s JSP file on how to set it up but I will reiterate them here:

  • Make sure to include the Apache Ant libraries; ant-launcher.jar and ant.jar that come with the current version of Ant.
  • You also need to include the tools.jar from your JDK lib directory.
  • And you need to have the Android SDK installed with the environment variable ANDROID_HOME set along with ANT_HOME and JAVA_HOME.
  • Make sure the BuildingServlet points to the example Android Application.
    /**
     * Change this to the directory of the Android application you want to build.
     * In the project I have been working on this is a file uploaded by the user
     */
    private static final String pathToAndroidFolder = "C:\\Users\\Lyndon\\Desktop\\antBroken\\BlankAndroid";
  • You might also need to change the sdk.dir in the local.properties file in the Blank Android  project.

After making sure that it’s set up right you can run the JSP and will get a screen like this:

testingJSP

Upon pressing submit the Application server your using will attempt to build the Android Project using Ant, for those interested it uses this simple piece of Java code:

    private void buildAndroidApp() {

        File dir = new File(pathToAndroidFolder);
        System.out.println("Current Android dir: " + dir.getAbsolutePath());
        File buildFile = new File(dir, "build.xml");

        Project project = new Project();
        project.setUserProperty("ant.file", buildFile.getAbsolutePath());
        project.setBaseDir(dir);

        DefaultLogger consoleLogger = new DefaultLogger();
        consoleLogger.setErrorPrintStream(System.err);
        consoleLogger.setOutputPrintStream(System.out);
        consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
        project.addBuildListener(consoleLogger);
        project.init();               

        ProjectHelper helper = ProjectHelper.getProjectHelper();
        project.addReference("ant.projectHelper", helper);
        helper.parse(project, buildFile);

        project.executeTarget("debug");
    }

If you were to run this outside of an application server as part of a normal Java program you will find no problems.

Upon running the JSP you will notice some errors in your GlassFish tab of NetBeans, or the build succeeding if you’re using Apache Tomcat.

You will then be presented with the Servlet’s response that will list any errors that occurred.

Ideally you would see this for both Tomcat and GlassFish:

tomcatSuccess

But sadly you will see this when run using GlassFish:

glassfishbug

If this article has been unclear I can potentially record a short video describing the problem. Hopefully it’s been informative for anyone wanting to help or experiencing the same issue. I know at least one other person who had the issue as they contacted me about it asking if I ever found a solution.

If you know the answer to this problem feel free to comment here and/or the Stack Overflow question I asked, I’d very much appreciate it.

Making my Raspberry Pi Tell Me the News

In my previous Raspberry Pi post I just told you quickly how to use your Pi to watch movies in a pinch, today I am going to walk through how I got my Raspberry Pi to speak out the current trending news headlines from reddit.com/r/worldnews.

To begin with I built a small Java application that made use of the freetts text to speech library and a Java wrapper for the Reddit API called jReddit. This worked well but the implementation seemed a bit too heavy for putting on the Pi, I had to make sure to have all the library files and make sure Java behaved itself etc.

For those interested you can see my Java Source file here. Please note it’s rather messy code and makes use of another time library.

So I opted to then recode it using Python since it came on with the Pi (as I am using a Linux based OS). In order to do this I needed to install a few Python modules for use, specifically pyttsx (the text to voice module) and praw (Reddit API module). Installing these was relatively easy using pip, the go to tool for installing Python modules.

Just to make sure you have python installed and to check the version you are running you can attempt to run the following command on your command line:

python --version

You should then see something along the lines of the following on your console output:

Python 2.7.3rc2

That is my version of python on my Raspberry Pi, yours will likely be similar! This isn’t a tutorial on Python programming itself (I know very little about it myself) but it’s worth mentioning there are some big differences between Python 3.x and Python 2.x, so programs written in one do not always work in the other.

Now in order to install modules easily I needed to install a module called pip.For this I found somebody had written a simple python script/program to do it for you. Instructions I found recommended running the following on the command line:

curl https://bitbucket.org/pdubroy/pip/raw/tip/getpip.py | python

This should pipe the contents of that url (it’s a pip installer someone made) into python to execute. Of course I ran into a problem doing this since I forgot to run this as a root user (by placing sudo in front of the command) and then resorted to downloading the script in the following and installing it with another command:

wget https://bitbucket.org/pdubroy/pip/raw/tip/getpip.py
sudo python getpip.py

As far as I know this will do the same thing, it installs pip so you can now easily install other packages/modules. And when I say easily, I mean easily. To install praw and pyttsx all I needed to do was the following:

sudo pip install praw
sudo pip install pyttsx

As easy as installing a Linux program using apt-get!

So after installing them I began my task of first learning Python. Having never coded in it before I found it surprisingly easy to get started in even with it’s strict white space rules. As a language it feels like it takes some of the best bits of C/C++ and JavaScript and rolls them together. I’ve yet to program anything Object Orientated in it yet but from the looks of it it’s easy to pick that up too.

To start with I wanted to test both modules separately. So after starting up an instance of the python interpreter (by running the command python) I typed the following:

import pyttsx
engine = pyttsx.init()
engine.say("Hello World!")
engine.runAndWait()

And got a bunch of errors to do with the ALSA library (that’s for the sound output cable I believe)! I then tried again and it worked through my HDMI lead. It also worked headless from an SSH connection with speakers plugged into the correct socket.

So now I had my Pi talking I needed to make sure I could get it something interesting to say. So I then wrote a simple python program to get the top ten news articles from Reddit based on the examples on praw’s documentation:

import praw
r = praw.Reddit(user_agent="Lyndon's news reader  by /u/LyndonArmitage")

subs = r.get_subreddit("worldnews").get_hot(limit=limit)
headlines = []
for sub in subs:
    print sub.title

This printed out the titles of the headlines to my console. Success!

Now I knew both of them were working I set out to translate my Java code to Python and dumped the Object Oriented aspects of it too simplify the problem. My code looked something like this:

import praw
import pyttsx
__author__ = "Lyndon Armitage"

engine = pyttsx.init()
r = praw.Reddit(user_agent="Lyndon's news reader  by /u/LyndonArmitage")

def get_headlines(limit=10):
    subs = r.get_subreddit("worldnews").get_hot(limit=limit)
    headlines = []
    for sub in subs:
        headlines.append(sub.title)
    return headlines

def speak_headlines(headlines=[]):
    for s in headlines:
        print s
        engine.say(s)
        engine.runAndWait()

titles = get_headlines()
speak_headlines(titles)

Assuming the modules are installed correctly it should also work for you! You might notice it’s pretty similar to both simple tests I made above. That shows how simple it was to make!

What I have done here is created two functions (using the keyword def), one returns a list of headlines from Reddit using praw and the other speaks them aloud using pyttsx. Very simple stuff.

And that’s it! I did create a modified version that will loop indefinitely (a bit like my Java version), only speaking at a set interval using Python but you can do similar things using cron on the Pi, which is my next step in playing with my Raspberry Pi!

What have you made with your Raspberry Pi? I’d love to get inspired by your ideas so please leave a comment below!

Blog Update & University Options

Blog Update

I haven’t posted in a while annoyingly, sorry about I’ve been busy with other responsibilities and it seems there aren’t enough hours in the day as I’d like there to be!

You may of noticed that I changed my blogs theme over to something simpler and brighter; I wasn’t to happy with the previous theme, although I did like the nice dark contrast it didn’t seem professional enough so I’ve opted for a slightly simpler theme. Hopefully it also makes reading the code I post a lot easier. At some point I hope to make my own theme or at least change one to suit my needs a bit better.

University

I’ve now chosen my final year options for my Computer Games Programming Course at DeMontfort University. For those who don’t know (or keep forgetting) I started my course over 2 years ago and am now over half way through a placement year. I had quite a few to pick from although not nearly as many as I’d of liked, they were:

  • Secure Web Application Development
  • Multi-Service Networks
  • Advanced Graphics
  • Mobile Robotics
  • Fuzzy Logic & Knowledge Based Systems (AI)
  • Systems Building: Methods and Management
  • Mobile Games
  • Audio Post-Production

I had to pick an amount that added up to 60 credits as I already have two compulsory modules worth 30 credits each (they all need to total 120).

  • My first choice was Mobile Games, because I have done some work on it before and enjoyed it. This is worth 30 credits.
  • My next choice was the Fuzzy Logic module, as I enjoy AI a lot and think it sounds interesting. This one is worth 15 credits.
  • I then only had 15 credits left to play with, which meant I could only pick between; Secure Web Application Development and Mobile Robotics. While I am interest in web applications the module description and presentation that we were given on it didn’t excite me. Whereas the description and presentation for Mobile Robotics interested me as it also involves a lot of Artificial Intelligence concepts. So I chose Mobile Robotics.

So now I have my options for next year I can sit back and relax right? Wrong! I’ve got to come up with a final year project before I start!

I have some ideas for this!

As you know if you’ve read some of my blog posts (including this one) I enjoy programming AI to do things, in fact some of my first blog posts were on an AI I made at university as part of a group project. So one of my ideas for a final year project is to attempt to create a framework for AI in a village for a role playing game like the Elder Scrolls series games have. That is, a system with NPCs who actively do things and perform daily tasks and follow routines working with and against one another. Hopefully I’d be able to make it a bit more complex than that though and include things like a simple economy and NPCs trading with one another.

If you have any thoughts on it or an idea that I might like feel free to leave a comment.

Other Stuff

Apart from all that I have still had time to create a few experiments; one of which being the start of a Fallout 3 Hacking Simulator and the other a program that will speak out the top news stories from Reddit using Python on my Raspberry Pi (blog post coming soon). I’m also still working on the second part to my Boids tutorial.

Playing Video Files on the Raspberry Pi from the command line

For the past 2-3 hours I have been watching movies on my television in my living room from a memory stick through my Raspberry Pi all without bothering with GUI interface and only using the command line interface to do it. And here’s how!

First I made sure that their was a media player installed that could be run from the command line, lucky for me I had one already installed called omxplayer and you probably do too! But in case you don’t here is the command to install it:

sudo apt-get install omxplayer

Of course you will need to be connected to the internet to use this but that’s the only time you will need to be connected for this tutorial so after installing omxplayer you can take your Pi wherever you like without worrying about an internet connection, which is handy because my living room hasn’t got one yet, and I have had trouble using my wireless dongle in the past.

To make sure it’s installed correctly, try running it:

omxplayer

You should get output that looks something like this:

Usage: omxplayer [OPTIONS] [FILE]
Options :
         -h / --help                    print this help
         -n / --aidx  index             audio stream index    : e.g. 1
         -o / --adev  device            audio out device      : e.g. hdmi/local
         -i / --info                    dump stream format and exit
         -s / --stats                   pts and buffer stats
         -p / --passthrough             audio passthrough
         -d / --deinterlace             deinterlacing
         -w / --hw                      hw audio decoding
         -3 / --3d                      switch tv into 3d mode
         -y / --hdmiclocksync           adjust display refresh rate to match video
         -t / --sid index               show subtitle with index
         -r / --refresh                 adjust framerate/resolution to video
              --boost-on-downmix        boost volume when downmixing
              --subtitles path          external subtitles in UTF-8 srt format
              --font path               subtitle font
                                        (default: /usr/share/fonts/truetype/freefont/FreeSans.ttf)
              --font-size size          font size as thousandths of screen height
                                        (default: 55)
              --align left/center       subtitle alignment (default: left)
              --lines n                 number of lines to accommodate in the subtitle buffer
                                        (default: 3)

Now you have omxplayer installed on your Raspberry Pi you can simply play media files on it and have the audio come out of the HDMI lead using the command:

omxplayer -o hdmi [Your-File-here]

But if like me you want to be able to play media off a memory stick plugged into your Raspberry Pi you will also need to mount it when it’s been plugged in! I found a good guide on how to do this here.

Basically the gist of it is that you need to create a directory in your /mnt/ folder for the device you want to mount, I went with the folder name usb:

sudo mkdir /mnt/usb

Then all you need to do is mount the drive to that directory using the command:

sudo mount /dev/sda1 /mnt/usb

NOTE: Your device might not be sda1! You will need to find out what device it is! I found a good tutorial about this here. Again, the gist of it is as follows:

Run the command:

tail -f /var/log/messages

Then simply plug in your memory stick and you should see a few messages appear telling you what your device is called.

Now you can run your mount command using the right parameters! After doing this you should then change directory to where you mounted the memory stick to (in my case /mnt/usb) and run omxplayer on the media using the aforementioned command.

Something to note about controlling playback is that from what I read on the omxplayer website there doesn’t appear to be a way of specifying a time stamp to start watching from, the only controls are:

z           Show Info
1           Increase Speed
2           Decrease Speed
j           Previous Audio stream
k           Next Audio stream
i           Previous Chapter
o           Next Chapter
n           Previous Subtitle stream
m           Next Subtitle stream
s           Toggle subtitles
d           Subtitle delay -250 ms
f           Subtitle delay +250 ms
q           Exit OMXPlayer
Space or p  Pause/Resume
-           Decrease Volume
+           Increase Volume
Left Arrow  Seek -30
Right Arrow Seek +30
Down Arrow  Seek -600
Up Arrow    Seek +600

But those are adequate enough for the most part! Hopefully this will come in handy for anyone not wanting to install XBMC!

Boids, Flocking Behaviour Tutorial Part 1: The Engine

The green circle represents their field of view.

Flicking through my Java games book some more I found a chapter on flocking, a subject a university tutor of mine only managed to mention in passing on our AI module due to time constraints. As I find AI quite interesting I thought I’d look into the subject some more so I decided to write my own 2D demo application of flocking behaviour akin to the original proposed by Craig Reynolds in his paper and on his website.

The Java book itself contained it’s version of a tutorial using awt but I decided to stick with a newer library that I have worked in before called Slick2D (See my tutorial on Game States as an example of my use of it before). I also decided to stick with 2D instead of 3D as the book demonstrates so I can keep things simple.

This first post is going to be about setting up the basic game engine I will be using as the underlying driving force of the game/demo.

 Step 1: Set up Slick

Slick needs a little bit of setting up before you begin making and testing your creations with it. This is relatively simple, add the jar files as libraries and make sure to include the LWJGL native files on your library path.

See the Slick2D wiki for details if you’re unsure how to do this.

If you are working in IntelliJ then you need to make sure to add the natives to your java.library.path in your run configurations like so:

RunConfig

For those too lazy to type that’s: -Djava.library.path=path/to/natives

 Step 2: Extend the BasicGame and Start Coding

The next step to take is to create a new class that extends Slick’s BasicGame class.

public class BoidsGame extends BasicGame {
	public BoidsGame(String title) {
		super(title);
	}

	@Override
	public void init(GameContainer gc) throws SlickException {
		//To change body of implemented methods use File | Settings | File Templates.
	}

	@Override
	public void update(GameContainer gc, int delta) throws SlickException {
		//To change body of implemented methods use File | Settings | File Templates.
	}

	@Override
	public void render(GameContainer gc, Graphics g) throws SlickException {
		//To change body of implemented methods use File | Settings | File Templates.
	}
}

The BasicGame class basically gets rid of a lot of the coding you need to do to create a game; in the words of the JavaDoc it is: A basic implementation of a game to take out the boring bits.

As you can see it needs to have a few methods over-ridden; init() is run once when we start the game and should contain all the initialization, update() and render() are both run each game frame. update() is where you should place game logic and  render() is reserved for drawing onto the screen. You also need to implement a constructor that takes the title of your game as a parameter.

Next we need a main method that will launch the game. In Slick we do this using an AppGameContainer object. I’ve also added a few constants and fields to my class that are used here:

	private static final int WIDTH = 800;
	private static final int HEIGHT = 600;
	private static int targetFrameRate = 30;

	private AppGameContainer container = null;

	public static void main(String args[]) {
		BoidsGame game = new BoidsGame("Boids - By Lyndon Armitage");
		AppGameContainer app;
		try {
			app = new AppGameContainer(game, WIDTH, HEIGHT, false);
			app.setShowFPS(false);
			app.setTargetFrameRate(targetFrameRate);
			app.setPaused(true);
			game.container = app;
			app.start();
		} catch (SlickException e) {
			e.printStackTrace();
		}
	}

This when run will show an empty window that is 800 by 600 pixels in size.

 Step 3: A Boid Skeleton

Next on the agenda is to make a start on the individual Boid code.

First create a new Class named Boid. Being a visual and non static creature we will need to implement a way of showing and updating the Boid so will create two methods that will be called by those in the previous class, update() and render():

	public void render(GameContainer gc, Graphics g) {

	}

	public void update(GameContainer gc, int delta) {

	}

Now we need to decide what the Boid will look like on screen and what properties it needs that will be changing.

  • A Boid needs:
    • A position in space. I choose to make this 2D so I opted for using a class built into Slick called Vector2f
    • A velocity. Again this is in 2D so I used Vector2f
    • A colour. Slick has a class for this called Color
    • An angle of where it is looking.
    • Height and width.
    • A shape. In keeping with the examples given on Boids I made them triangular
    • A field of view. To keep things simple I am using a whole circle around the Boid. A better way of doing this would be to chop out a section of the circle behind the boid so it cannot see behind it.

     

So what do these all look like?

	private float angle = 0f;
	private Vector2f pos;
	private Vector2f vel;
	private Color color;

	private static final float width = 8;
	private static final float height = 10;
	private static final int lineWidth = 1; // how many pixels thick the lines are

	private static final float viewDistance = 50f;

I’ve used static final values for things that I will not be changing during the simulation/game. Onto the code using these!

Firstly I implemented the basic code to update the position of the Boid based only on the velocity, this is quite simple:

		pos.x += vel.x / delta;
		pos.y += vel.y / delta;
		if (pos.x > gc.getWidth()) {
			pos.x = gc.getWidth() - pos.x;
		}
		if (pos.y > gc.getHeight()) {
			pos.y = gc.getHeight() - pos.y;
		}
		if (pos.x < 0) {
			pos.x = gc.getWidth();
		}
		if (pos.y < 0) {
			pos.y = gc.getHeight();
		}

Delta, for those who do not know what it is, is the time between frames and is used to ensure that everything is synced up and independent of the frame rate. In this example I also made the Boids play area loop round from top to bottom and left to right.

For this to work we need to initialize some of the objects we declared as variables. For this I created an init() method that I call from various constructors:

	public Boid() {
		init(0f, 0f, Color.white, 0f, 0f);
	}

	public Boid(float x, float y) {
		init(x, y, Color.white, 0f, 0f);
	}

	public Boid(float x, float y, Color color) {
		init(x, y, color, 0f, 0f);
	}

	public Boid(float x, float y, Color color, float velX, float velY) {
		init(x, y, color, velX, velY);
	}

	public Boid(float x, float y, float velX, float velY) {
		init(x, y, Color.white, velX, velY);
	}

	private void init(float x, float y, Color color, float velX, float velY) {
		pos = new Vector2f(x, y);
		vel = new Vector2f(velX, velY);
		this.color = color;
	}

These should cover all the ways I could want to create a Boid. We also need to add some getters for later use as I made all of the variables we defined private.

	public Color getColor() {
		return color;
	}

	public Vector2f getPos() {
		return pos;
	}

	public Vector2f getVel() {
		return vel;
	}

But wait, we can now update the Boids position but we still can’t see them! So we need to make the render() do something.

Below is the code I used to render the Boids, note that I made use of the graphics context given to us by Slick, a better way of drawing a triangle would of been to use LWJGL’s OpenGL methods directly  but opted to use Slick’s methods to show them off:

	public void render(GameContainer gc, Graphics g) {
		//g.drawString("boid", pos.x, pos.y);
		g.rotate(pos.x, pos.y, angle);
		g.setLineWidth(lineWidth);
		g.setColor(color);
		g.drawLine(pos.x - (width / 2), pos.y - (height / 2), pos.x + (width / 2), pos.y - (height / 2)); // bottom line
		g.drawLine(pos.x + (width / 2), pos.y - (height / 2), pos.x, pos.y + (height / 2)); // right to top
		g.drawLine(pos.x, pos.y + (height / 2), pos.x - (width / 2), pos.y - (height / 2)); // top to left
		g.resetTransform();
	}

Hopefully these method calls are pretty self explanatory; I first rotate the context, then I set the line width and colour, followed by drawing the lines and finally resetting the rotation. The lines are each drawn separately, first the bottom line of the triangle, next the right hand side line and last the left hand side line.

Step 4: Some Intelligence for the Boid

Now we have our basic Boid Skeleton code; we can see them and they can move but they have no intelligence so now we need to give them a brain just like the Scarecrow in Oz wanted!

The first thing I a Boid needs to be able to do is know the angle between itself an other Boids. To do this we can use a mathmatical function called the arctangent that when supplied with two values derived from the difference between two points will return the angle between them. In my code I implemented this function like this:

	private float getAngleToBoid(Boid target) {
		float deltaX = target.getPos().x - pos.x;
		float deltaY = target.getPos().y - pos.y;
		float angle = (float) (Math.atan2(deltaY, deltaX) * 180 / Math.PI);
		angle -= 90; // seems to be off by 90 degrees probably due to how the graphics are set up
		if (angle > 360f) {
			angle = 360f - angle;
		} else if (angle < 0f) {
			angle = 360f + angle;
		}
		return angle;
	}

Like most programming languages and libraries Math.atan2() returns an angle in radians so we need to convert these to degrees for our use, that’s what the multiplication and division by pi are for.

Next the Boid also needs to be able to discern the distance between it and other Boids, this is a very simple method to implement since it uses a well known forumla for measuring distance on a grid:

	private float getDistanceToBoid(Boid target) {
		Vector2f v = target.getPos();
		return (float) Math.sqrt(Math.pow(v.x - pos.x, 2) + Math.pow(v.y - pos.y, 2));
	}

And finally a Boid should also be able to figure out if another Boid is within range of it or not. The method I made to do this makes use of Pythagoras to check if it is with a circle around the Boid:

	private boolean isBoidInView(Boid target) {
		float dx = Math.abs(target.getPos().x - pos.x);
		float dy = Math.abs(target.getPos().y - pos.y);
		float radius = viewDistance / 2;
		if (dx > radius) {
			return false;
		}
		if (dy > radius) {
			return false;
		}
		if (dx + dy <= radius) {
			return true;
		}
		// Pythagoras here
		if (Math.pow(dx, 2) + Math.pow(dy, 2) <= Math.pow(radius, 2)) {
			return true;
		} else {
			return false;
		}
	}

It also does some checks beforehand to make sure we need to use Pythagoras.

Step 5: Add some Boids and test!

Up until now we havent added any Boids to the actual engine to test. In fact the engine doesn’t have any logic as of yet for dealing with the Boids. What we now need to do is write the code for the update() and render() methods!

This code is quite simple since the logic for the Boids will be contained within the Boids themselves. All I have done is added an ArrayList of Boids to the main game class and some code that loops through each Boid within calling their respective methods:

	private ArrayList boids = null;
	@Override
	public void init(GameContainer gc) throws SlickException {
		Random rnd = new Random();
		boids = new ArrayList();
		// add the boids
		Boid boid1 = new Boid(WIDTH / 2, HEIGHT / 2, rnd.nextInt(100), rnd.nextInt(100));
		boids.add(boid1);
		Boid boid2 = new Boid(WIDTH / 4, HEIGHT / 2, rnd.nextInt(100), rnd.nextInt(100));
		boids.add(boid2);
		gc.setPaused(false);
	}

	@Override
	public void update(GameContainer gc, int delta) throws SlickException {
		//System.out.println(delta);
		for (Boid b : boids) {
			b.update(gc, delta, boids);
		}
	}

	@Override
	public void render(GameContainer gc, Graphics g) throws SlickException {

		if (drawGrid) {
			drawGrid(g);
		}

		for (Boid b : boids) {
			b.render(gc, g);
			if (drawArc) {
				b.renderArc(g);
			}
		}

		if (debugOn) {
			g.setColor(Color.green);
			g.drawString("0,0", 10f, 0f);
			g.drawString(WIDTH + "," + HEIGHT, WIDTH - 65, HEIGHT - 18);
		}
	}

Notice that I have changed the method signature of the Boid method update() to include a reference to the ArrayList, this way we can tell each Boid were each of them are and develop behaviour accordingly. For example, this code will make a Boid look at the closest other Boid within range:

	public void update(GameContainer gc, int delta, ArrayList boids) {

		// some look at the closest boid in view code
		Boid target = null;
		float dist = 0;
		for (Boid b : boids) {
			if (b.getPos().x == pos.x && b.getPos().y == pos.y || !isBoidInView(b)) continue;
			if (target == null || getDistanceToBoid(b) < dist) {
				dist = getDistanceToBoid(b);
				target = b;
			}
		}
		if (target != null) {
			angle = getAngleToBoid(target);
		}

		updatePos(gc, delta); // This contains the original update() code
	}

Also you will notice references to debug features I added; including drawing the view arc around each Boid drawing a grid and drawing out the min and max coordinates in view.

When run at this stage we should get something similar to this when the two Boids go within range of each other:

The green circle represents their field of view.

The green circle represents their field of view.

The source code for this tutorial can be found on GitHub here: https://github.com/LyndonArmitage/Boids

The next part will hopefully deal with adding the various Flocking behaviours Separation, Alignment and Cohesion. For more information on Boids please visit Craig Reynolds website: http://www.red3d.com/cwr/boids/

Edit:

A flaw in the way I had my boids reacting to each other was exposed by Amndeep7 on Reddit, see the original comment here.

I had overlooked the fact that each time I updated a Boid their new values were then used by the next Boid in the loop, this meant that the results would not be valid. The original comment has a much better explanation than this so I encourage you to have a look at it. As for the code in this tutorial I will address the issue in the concluding post so for now I leave it as an exercise for the reader to figure out how to solve this problem, feel free to leave suggestions and solutions in the comments.

Personal Project: LMinify, CSS and JavaScript Minifier

Recently at work we have been looking at ways of reducing file size of our HTML, CSS and JavaScript files. One such way for the last two is to minify them; that is to strip out the unneeded parts of them like comments, extra spacing, line breaks etc.

To my pleasant surprise I found there to be quite a lot of tools out there that do the job! As we develop in Java and I didn’t want to spend too long at work looking for a solution I decide to use a library called YUI Compressor; being all written in Java all I had to do was write some code to apply to some of our generated files. I then later found out that this specific library isn’t being developed for any more which is a bit of a bummer (it seems to do a good job!).

After seeing the results I was left a little intrigued in how such a library works so decided to begin writing one myself!

So I did!

So I did! (Also anyone else love Dark IDE skins?)

So far it only works on CSS (files and text strings) but seems to shrink them quite well! I had already implemented a method for replacing calls to rgb(r, g, b) with their corresponding hex colour and hope to flesh the library out some more. I have yet to look at the source code of YUI Compressor and am sure when I do I will learn a thing or two about what to do in my library.

I’ve called it LMinify, it’s more of a pet project than a professional tool like some the programs I found (feel free to use it if you like though). I am hoping to keep it’s dependencies low (currently the only external Library in use is Junit for the tests!) and am also hoping making it will teach me a thing or two and maybe come in handy at work!

It can be found here: https://github.com/LyndonArmitage/Lminify

 

while(true) BadPractices(); continue;

Recently I have been flicking through a Java book on games programming that I was fortunate enough to pick up for free on my trip to JavaOne (thank you nice people on the O’Reilly stand, and Andrew from StrongAuth for saving it for me!). While slightly out of date (it was written for Java 1.4 or 5) it still has many interesting explanations and examples of useful code and techniques for making games.

One part that interests me and caused me to write this blog article, is the networking section of the book. Within this section it shows off how to use Sockets to create a basic Score Server for a game. It’s very good at explaining it with the code divided up between explanations of what it does but it contains within it a certain statement I was taught to avoid when learning to program. That statement is within the title of this blog post; while(true).

Although in the given situation you may want to have your server loop running virtually forever I am still a little dubious that using a while(true) loop is really the necessary way of handling, and looking into the JavaDocs of the ServerSocket class there is a function called isClosed() that would be better suited to be the task and allow the server socket to be closed when needed and exit cleanly.

However, this may just be a coding practice that has been banged into my head from College and University, so what are your opinions on it? Is it a bad practice? Or is it acceptable given there is a breaking statement somewhere in the loop (in this example there was none)?

I made a quick Java Program showing code based off of the example from the book, including the while(true) loop. You can see it here on my github.

Also, sorry if the title confuses or offends anyone, I thought it was quite clever…

Making Tic Tac Toe for Android

Live on my phone

In my last blog post I showed a little cheating application I made for the Android which is sort of related to games (word games to be precise) so today in this post I thought I’d explain how I made a simple Tic Tac Toe Application for the Android phone (that’s Noughts and Crosses for us Brits).

Setting Up

First of all you create a new Android project in whatever IDE you are using, I am using IntelliJ Idea so I went to File|New Project:

I have it in it's Dark Theme

I have it in it’s Dark Theme

In Eclipse you would go to File|New|Android Application Project:

I quite like the configuration options you get here.

I quite like the configuration options you get here.

I have a few SDKs installed on my machine including the latest, the one my phone runs on and the one just below what my old phone ran on (2.2) so to make sure this worked for the most devices I opted for an SDK versions in the 2′s (I ended up using 2.3, Gingerbread).

Next I set up a few things in the files, nothing to major to note about, I did make a mistake in my Project name that I just corrected in one of the xml files but decided not to change it at an actual project level (partly to do with the fact I had already created and pushed a GitHub page under the name).

The Layout

The next thing I did was design the application layout. The file in my case was generated and called main.xml and was located in the res folder under the layout subfolder, it may of been called something else in an Eclipse project but it should be the only file located in that subdirectory.

This was relatively easy as Idea has a very nice UI designing tool, as does Eclipse. I settled on this:

DesignIdea

That’s:

  • A TextView with my name and the title of the game in it.
  • A Button with the words New Game in it.
  • A TableLayout containing within a Button in the 1st, 2nd and 3rd cell of 3 different rows.

I have modified each item to look how I would like them to look:

  • The TextView has had it’s layout:gravity set to centre it horizontally.
  • The Button has also had it’s layout:gravity set to centre it horizontally. And has also had it’s layout:width set to fill the parent.
  • The TableLayout has had it’s layout:gravity set to centre both horizontally and vertically.
  • Each Button within the TableLayout have had their width and height attributes set to 100dp so they appear square.

I won’t show you the actual xml file for this in it’s pure form as I think it’s better you experiment yourself.

I also modified the AndroidManifest.xml file (located at the root of your project) to prevent the application being rotated into landscape by adding:

android:screenOrientation="portrait"

To the activity tag.

Onto the Code

Now finally the code!

When you begin a new Android project you are probably presented with a java file similar to this (minus the comments and typo):

package com.example.NaughtsAndCrosses;

import android.app.Activity;
import android.os.Bundle;

/**
 * Tic Tac Toe Game
 * ---
 * 
 * Code by Lyndon Armitage
 * For learning purposes
 *
 * @author Lyndon Armitage
 */
public class MainActivity extends Activity {
	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}
}

Our first port of order is deciding how we are going to represent the game state. So to do this we need to establish some facts namely;
there are only 2 players (X and O) and the board is laid out in a 3 by 3 grid of either Xs, Os or blanks.

From these facts I decided to go with:

	// Representing the game state:
	private boolean noughtsTurn = false; // Who's turn is it? false=X true=O
	private char board[][] = new char[3][3]; // for now we will represent the board as an array of characters

An alternative to using the char array is using an array of an Enum but a simple char array will do for now. Likewise I could of also used an Enum for determining who’s turn it was.

Now we know how we are going to represent the game state we need to figure out how we are going to interact with it. Technically I already decided this, by using Buttons in a TableLayout and a button outside it to start a new game.

The first thing I decided to get working was interacting with each button in the layout; changing what they have written on them and what they do when clicked. This was actually more complicated to code than I expected. Originally I thought there would be a simple call to the TableLayout to get the element in a certain position, something like getViewAt(int x, int y) but there was not. This is because the TableLayout can contain data not in rows and columns, e.g. it can contain an EditText Element below or in between it’s normal TableRows. Example:

Good come in handy actually

Could come in handy actually

When you think about it this makes sense in designing a layout, it means you can have heading for different parts of the grid.

So in order to get the position of each button we have to look at each of the TableRow objects contained within it and use their positions as the y coordinate and the Buttons position within them as the x coordinate:

	/**
	 * This will add the OnClickListener to each button inside out TableLayout
	 */
	private void setupOnClickListeners() {
		TableLayout T = (TableLayout) findViewById(R.id.tableLayout);
		for(int y = 0; y < T.getChildCount(); y ++) {
			if(T.getChildAt(y) instanceof TableRow) {
				TableRow R = (TableRow) T.getChildAt(y);
				for(int x = 0; x < R.getChildCount(); x ++) {
					View V = R.getChildAt(x); // In our case this will be each button on the grid
					V.setOnClickListener(new PlayOnClick(x, y));
				}
			}
		}
	}

I will explain what PlayOnClick is in a moment. What that code does is it grabs the tableLayout and loops through each of it’s children (making sure each one is a TableRow) and then loops through each child’s children and sets up what they do upon a click. I had to edit my TableLayout and give it an ID to it in order to find it using findViewById() I simply set up it’s android:id attribute in the xml to:

android:id="@+id/tableLayout"

PlayOnClick is a custom OnClickListener I created for this program. I could of instead created 9 different methods (one for each button) and set each button to call one each using the UI designer but instead opted to create an OnClickListener and dynamically set each button to use one with it’s unique coordinates.
An implementation of this for our game looks like this (it’s an inner class of my MainActivity class):

	/**
	 * Custom OnClickListener for Noughts and Crosses
	 * Each Button for Noughts and Crosses has a position we need to take into account
	 * @author Lyndon Armitage
	 */
	private class PlayOnClick implements View.OnClickListener {

		private int x = 0;
		private int y = 0;

		public PlayOnClick(int x, int y) {
			this.x = x;
			this.y = y;
		}

		@Override
		public void onClick(View view) {
			if(view instanceof Button) {
				Button B = (Button) view;
				board[x][y] =  noughtsTurn ? 'O' : 'X';
				B.setText(noughtsTurn ? "O" : "X");
				B.setEnabled(false);
				noughtsTurn = !noughtsTurn;
			}
		}
	}

Now if you were to run this as it was it would be a playable version of Tic Tac Toe, albeit without any score tracking and win checking. Not only that but, the New Game Button does nothing, so let’s change that.

	/**
	 * Called when you press new game.
	 * @param view the New Game Button
	 */
	public void newGame(View view) {
		noughtsTurn = false;
		board = new char[3][3];
		resetButtons();
	}

	/**
	 * Reset each button in the grid to be blank and enabled.
	 */
	private void resetButtons() {
		TableLayout T = (TableLayout) findViewById(R.id.tableLayout);
		for (int y = 0; y < T.getChildCount(); y++) {
			if (T.getChildAt(y) instanceof TableRow) {
				TableRow R = (TableRow) T.getChildAt(y);
				for (int x = 0; x < R.getChildCount(); x++) {
					if(R.getChildAt(x) instanceof Button) {
						Button B = (Button) R.getChildAt(x);
						B.setText("");
						B.setEnabled(true);
					}
				}
			}
		}
	}

I set the New Game button to call the corresponding method using my UI editor and now when I click it I clear the grid. I also added a call resetButtons() into the onCreate() method to make sure all the buttons are blank.

Now what about checking for a win? Well I know that whenever 3 of the items in a line match that specific player has won so let’s go about coding a method that works this out and appropriately responds.

Below is my implementation of a method that can check if a specific player has won at a game of tic tac toe for any size board, it could probably be improved and simplifed into only one loop but that may be harder to understand:

	/**
	 * This is a generic algorithm for checking if a specific player has won on a tic tac toe board of any size.
	 *
	 * @param board  the board itself
	 * @param size   the width and height of the board
	 * @param player the player, 'X' or 'O'
	 * @return true if the specified player has won
	 */
	private boolean checkWinner(char[][] board, int size, char player) {
		// check each column
		for (int x = 0; x < size; x++) {
			int total = 0;
			for (int y = 0; y < size; y++) {
				if (board[x][y] == player) {
					total++;
				}
			}
			if (total >= size) {
				return true; // they win
			}
		}

		// check each row
		for (int y = 0; y < size; y++) {
			int total = 0;
			for (int x = 0; x < size; x++) {
				if (board[x][y] == player) {
					total++;
				}
			}
			if (total >= size) {
				return true; // they win
			}
		}

		// forward diag
		int total = 0;
		for (int x = 0; x < size; x++) {
			for (int y = 0; y < size; y++) {
				if (x == y && board[x][y] == player) {
					total++;
				}
			}
		}
		if (total >= size) {
			return true; // they win
		}

		// backward diag
		total = 0;
		for (int x = 0; x < size; x++) {
			for (int y = 0; y < size; y++) {
				if (x + y == size - 1 && board[x][y] == player) {
					total++;
				}
			}
		}
		if (total >= size) {
			return true; // they win
		}

		return false; // nobody won
	}

I call the above method within another that handles what to do if a player has won:

	/**
	 * Method that returns true when someone has won and false when nobody has.
	 * It also display the winner on screen.
	 *
	 * @return
	 */
	private boolean checkWin() {

		char winner = '\0';
		if (checkWinner(board, 3, 'X')) {
			winner = 'X';
		} else if (checkWinner(board, 3, 'O')) {
			winner = 'O';
		}

		if (winner == '\0') {
			return false; // nobody won
		} else {
			// display winner
			TextView T = (TextView) findViewById(R.id.titleText);
			T.setText(winner + " wins");
			return true;
		}
	}

The TextView I describe there is the same one that has my name in it when you look back to the design, this way the players can see who has won.

Now we simply need to edit the onClick method of our PlayOnClick class to utilise this method correctly:

		public void onClick(View view) {
			if (view instanceof Button) {
				Button B = (Button) view;
				board[x][y] = noughtsTurn ? 'O' : 'X';
				B.setText(noughtsTurn ? "O" : "X");
				B.setEnabled(false);
				noughtsTurn = !noughtsTurn;

				// check if anyone has won
				if (checkWin()) {
					disableButtons();
				}
			}
		}

The method disableButtons() simply disables all the buttons within the grid to stop you playing after a win.

And that’s it! Tic Tac Toe on Android step by step!

Live on my phone

Live on my phone

I have a GitHub Repository with all this code available here if you want to see the finished code.

Possible improvements include;

  • Score keeping.
  • Bigger grids.
  • Online play.
  • An AI to play against.
  • Pretty Colours.
  • Optimisations.

If you want to use the code feel free, provided you aren’t making money off of it or calling it your own (it took me time and effort to make it after all).

Happy Coding!

An Android App: Word Wheel Helper/Solver

Screenshot_2013-01-10-20-34-34

Well I did it! I optimised my Word Wheel Solver and turned it into a functional Android Application!

Screenshot_2013-01-10-20-34-34

Pretty Spiffy eh?

That’s a screenshot from earlier tonight when I got it working.

Since then I recoded the way it searched for words so it now uses an ASyncTask object. This means that it doesn’t sit there and halt for a moment while doing it’s business.

Now I have the basic application working, and working well I’m looking into adding other features and polishing it up. I need a logo for it for one thing and as you saw in my previous blog post my pixel art skills using MS Paint aren’t the best…

I am quite impressed with it as it stands at the moment and will see about releasing it on the Google Play Store when I register as a developer on it and figure out how (any links/tutorials on how to get an app on the market would be nice).