Writing Java Games with Slick. Part Two: Hello World!

Posted: February 8, 2011 by jellymann in computers, java, programming, tutorials

After setting up your Eclipse Project (see Part One) you can begin programing your game! This part of the tutorial deals with the basics of a Slick Game and how to draw text, shapes, and images.

1. Getting Started

In Eclipse, right-click on ‘src’ in your project and select New > Package. Call it ‘slick.tutorial’. You should see it inside your project:

Note: For those unfamiliar with Java, packages work like folders (they are represented by folders in your file manager). For example, slick.tutorial would appear in your file manager as [workspace]/Slick Tutorial/src/slick/tutorial. Packages inside packages are separated by a period instead of a slash.

Right-click on the package and select New > Class. You should see a window like this:

Type ‘TutorialGame’ into Name.
Enter ‘org.newdawn.slick.BasicGame’ into Superclass.

Tip: You can use Eclipse’s neat Autocomplete here. Just type ‘BasicGame’ in the text-box and press Ctrl-Space. It should put in the rest for you.

Make sure ‘public static void main(String[] args)’ and ‘Constructors from superclass’ is checked.

You should see your new class in the main window, with ‘init’ ‘update’ and ‘render’ automatically added. These methods are necessary for creating a game in Slick.

2. Adding the basics

BasicGame contains all the basics for creating a simple game in Slick. As you can see, there are three main methods that were automatically added. I will explain them.

init is called when the game starts. You can put code here to set things up for your game, such as loading resources like images and sounds.

update is called periodically, usually every 20 milliseconds, but the time will vary depending on how much processing you’ll be putting in. This is where the game logic is done.

render is called constantly. This is where all your graphics is done.

Then there is main. Everything starts here. Let’s put in the first few lines of code to get things going.

Every game needs to be put into a GameContainer to be viewed. We are using AppGameContainer, which puts our game into a window. Place these lines inside the main method:

TutorialGame game = new TutorialGame("Slick Tutorial");
AppGameContainer container = new AppGameContainer(game);
container.start();

AppGameContainer will probably be underlined in red at this point. If it is, you need to add it to your list of imports. Eclipse makes this easy, just click on AppGameContainer in your code and press Ctrl-1. A menu should pop up like this:

Double-click on the first option “Import ‘AppGameContainer’ (org.newdawn.slick)”.

Tip: You can always use Eclipse’s ‘Quick Fix’ (Ctrl-1) whenever there is an error in your code.

There will probably still be an error at new AppGameContainer(game); This is because it throws an exception and we need to place it in a try/catch block. I won’t go into detail about exceptions at this moment. What we will do now is use Quick Fix to automatically surround this piece of code in a try/catch block. Click on the underlined code and press Ctrl-1 then double-click “Surround with try/catch”. It should be the second option. Don’t worry about code underlined in yellow at the moment, those are just harmless warnings.

You main method should look something like this:

public static void main(String[] args) {
     TutorialGame game = new TutorialGame("Slick Tutorial");
     try {
          AppGameContainer container = new AppGameContainer(game);
          container.start();
     } catch (SlickException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
     }
}

Now run this by pressing Ctrl-F11. If you did everything right, you should see a black window pop up showing frames per second in the corner.

3. Saying Hello

Now let’s put a something on the screen. It’s as easy as putting this in your render method:

g.drawString("Hello World!",200,200);

You should see this when you run it:

Now let’s add a bit of color. This is done easily by putting in a g.setColor(Color) before drawing the text. Slick comes with a few preset colors, but there are numerous ways to make your own colors. Here are some examples of ways you can set the color:

g.setColor(Color.red); // Preset Color Red
g.setColor(new Color(0,255,150)); // A  yucky green defined using three integers
g.setColor(new Color(1.0f,0.5f,0.5f,0.8f)); // A light purple with 80% transparency defined using four floats
g.setColor(new Color(0x7b2900)); // A brown-reddish defined using hex

You can also draw various shapes, such as rectangles, ovals and lines, by using g.drawRect(x,y,w,h); g.drawOval(x,y,w,h); and g.drawLine(x1,y1,x2,y2); These methods only draw an outline. You can draw filled objects by using g.fill instead of g.draw (You obviously can’t fill a line, though). There are more shapes you can draw and fill. Experiment with them 🙂

The following code:

g.setColor(new Color(0xff00ff)); // Luminous pink!
g.drawString("Hello World!",200,200);

g.setColor(Color.blue);
g.drawRect(180, 170, 150, 80);

g.setColor(Color.red);
g.drawLine(250, 190, 300, 230);
g.drawLine(250, 230, 300, 190);

g.setColor(new Color(0f,0.6f,0.8f,0.5f)); // transparent bluish, 50% transparent
g.fillOval(190, 180, 60, 60);

Should make this picture:

If you want to smooth the jagged edges, put g.setAntiAlias(true); before everything. You can also apply anti-aliasing to specific things, by turning it on and off before drawing things. For instance, if we wanted the red cross smoothed but leave the circle we would turn on anti-aliasing before drawing the lines and then turn it off before filling the circle.

g.setColor(new Color(0xff00ff)); // Luminous pink!
g.drawString("Hello World!",200,200);

g.setColor(Color.blue);
g.drawRect(180, 170, 150, 80);

g.setAntiAlias(true);
g.setColor(Color.red);
g.drawLine(250, 190, 300, 230);
g.drawLine(250, 230, 300, 190);

g.setAntiAlias(false);
g.setColor(new Color(0f,0.6f,0.8f,0.5f)); // transparent bluish, 50% transparent
g.fillOval(190, 180, 60, 60);

As you can see, text is automatically anti-aliased.

4. Adding Images

I’ve found that slick is much more efficient at drawing images that shapes. I don’t know the technical details, but it’s not a train-smash, as your game will probably use a lot of images and not that much geometry.

For the next bit, we’re going to need some images. For the tutorial I’m going to use the ones pictured below.

First, declare the images before everything else, like this:

public class TutorialGame extends BasicGame {

	Image arrow;
	Image triangle;

	...

Remember, you will need to import Image from Slick. Using Quick Fix, make sure you select the right one (org.newdawn.slick), because there will also be the option to import Image from Java2D (java.awt).

Then, load the resources in the init method. Remember, all resource loading must be done inside init. Make sure your images are in your project folder.

public void init(GameContainer container) throws SlickException {

	arrow = new Image("arrow.png");
	triangle = new Image("triangle.png");

}

Now you can draw the images by simply putting g.drawImage(Image,x,y);in the render method, where x,y is where the top-left corner of your image will be drawn. e.g. g.drawImage(arrow,50,100);

There are some other things you can do with an image, like scaling/stretching it, drawing only parts of it, and changing its color.

Try doing this and see what you get:

// draws the images at the specified positions
g.drawImage(arrow,50,100);
g.drawImage(triangle,100,200);

// draws the image, but with green
g.drawImage(arrow, 150, 100, Color.green);

// To draw the image transparent
// use white as the colour and set the alpha
// the following draws the image at 50% transparency
g.drawImage(arrow, 250, 100, new Color(1f,1f,1f,0.5f));

// draws a part of the image
// a 50x60 snippet at 20,10 on the image
// drawn at 300,200 on the screen
g.drawImage(triangle,
	300, 200, // where you want the top-left of the snippet to be
	350, 260, // bottom-right "
	20, 10, // top-left of the snippet relative to the image
	70, 70); // bottom-right "

// draws the image at twice the size
g.drawImage(arrow,
	50, 350,
	50+arrow.getWidth()*2,
	350+arrow.getHeight()*2,
	0, 0,
	arrow.getWidth(),
	arrow.getHeight());

The snippet there works like this:

You can also stretch the snippet to your liking by changing x2,y2.

It’s usually good practice to place your images and other resources in a ‘res’ folder next to your ‘src’ folder. Then your images will be accessed by new Image("res/imagename.png");

Slick can read a number of image formats, including png, gif and jpg.

This concludes our lesson for today. Next Up we’ll have a look at making things move around in the update method.

Advertisements
Comments
  1. igeneric says:

    A good read! Nice article! When can we expect so see some more? Do you plan on sharing the code for your game?

  2. bwochinski says:

    Cool to read your tut, I just started messing around with Slick about a month ago. I had a little bit of test code working, but naturally I’ve gotten distracted by Minecraft and other interests, so never got any further.

  3. A. J. Wright says:

    Great tutorial!

    I’d be curious to see a discussion on how to go from what you’ve started here (Eclipse + Slick) to a runnable Jar file.

  4. MaTachi says:

    Nice post! Thanks for sharing. =)

  5. Sybren Gjaltema says:

    Nice, this helped me a lot 🙂
    Any clue when Part 3 is coming out?

  6. Rikku says:

    The image I’m drawing displays a diagonal line right across it D:

  7. Dylan Haughton says:

    could you do more of this?

  8. nike4613 says:

    Did anyoune ele get “Exception in thread “main” java.lang.UnsatisfiedLinkError: org.lwjgl.DefaultSysImplementation.getPointerSize()I”

  9. John says:

    I have followed all of the last step but Eclipse wants me to setup the run configuration, it says there is no launch configuration even though I followed the last step. As a side note I am using portable Eclipse on my USB and I had to setup run configurations to run previous java projects.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s