Programming Games in JavaFX - Part 1

This is the first of a 6 part tutorial on game programming with JavaFX. JavaFX is well suited for games because of it's focus on user interactivity and rich animation. I am a novice game programmer; I recently took my first class in Java game programming and I decided to do my final project using JavaFX.  I found it to be a really great platform that is easy to learn and powerful enough to do some fancy things with a small amount of code.

I've designed each tutorial to be quick and easy to digest. And when you reach the end you'll have a fully functional game based on what I consider to be the mother of all video games. We'll be creating a game called Blasteroids. If you'd like to see the final result of this tutorial, click here to launch the game.  It should take about an hour to complete all of the lessons in this tutorial. If you'd like to download the completed project, including all the files, click here.

Although you don't have to be an advanced programmer to follow along, it will really help if you know some of the basics of the JavaFX programming language (you'll also have to know how to create a new JavaFX project in NetBeans). Depending on your background in programming, some of the syntax and control structures can seem a little odd at first glance. Sun's website has some great resources for getting familiar with the language.  For more information, go to javafx.com, or there's a great, and FREE, online course at javapassion.com.

There's just one more thing I'd like to do before we get started.  I want to give credit to the people who helped me in my quest to create this game.  First, I'd like to thank Scott Finn for teaching a great class, Beginning Java Game Development, at Western Technical College.  I also want to mention that I wouldn't have been able to get this project started without the help of Liu Xuan's website, which has the source code for a game that he developed. I got a lot of valuable information from a book by Johnathon Harbour, it's called Beginning Java Game Programming and I highly recommend it.  Finally, I got started using JavaFX by signing up for a really excellent free course that's hosted by Sang Shin and James Weaver.  If you're interested, go to www.javapassion.com.

Now, let's get started. I used NetBeans 6.5.1 for my development environment, to download it, along with the latest version of JavaFX, visit Sun's website.  In this first lesson, we will just set up a few files that make up the architecture of our game and the result will be a ship that is placed in the middle of the screen. 

Go ahead and create a javaFX project called 'Blasteroids' in NetBeans. We will create four classes that serve as the foundation for our game.  Main.fx serves as the application driver class, and this will launch all of the other classes.  Config.fx will hold all of our settings for the game, such as how fast the ship can move and how many bullets it can fire. Ship.fx will render the image of our ship.  The most interesting class is Container.fx.  This class will serve as our game engine and it will control all objects, handle all the keyboard events, and control all of the action that happens on the screen. Bear with me in this first lesson, it has the most amount of code. In future lessons we'll occasionally add a new class, but mostly we'll be adding code to these four classes.

 

So here we go, we'll start with Main.fx.  You'll notice that it simply creates an instance of the Container class and places it into the content of the scene. Here's the code for Main.fx:

 

package blasteroids;

import javafx.stage.Stage;
import javafx.scene.Scene;

Stage {
    title: "BLASTEROIDS"
    width: Config.SCREEN_WIDTH
    height: Config.SCREEN_HEIGHT;
    resizable: false
    onClose: function(){
        java.lang.System.exit(0);
    }
    scene: Scene {
        content: [
            Container{}
        ]
    }
}

 

Next we'll create our configuration file, it's nice and small right now, but it will grow as we add more features to our game. Here's the code for Config.fx:

 

package blasteroids;

public def SCREEN_HEIGHT:Integer = 800;
public def SCREEN_WIDTH:Integer = 1200;

 

Next we'll create our game engine class which will contain all of the objects in the game and control their interaction.  Notice that this class has a Group object called 'gameBoard' and that it's content property holds our ship. We'll call this class Container.fx. Note that I'll include all the imports that we'll need for later lessons now, so you'll see some warnings from NetBeans saying that you have 'unused imports' until we actually put them all to use.  Here's the code for Container.fx:

 

package blasteroids;

import blasteroids.Config;
import blasteroids.Ship;
import java.lang.Math;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import java.util.Random;

public class Container extends CustomNode {
    public var ship: Ship = Ship{
        posX: Config.SCREEN_WIDTH / 2
        posY: Config.SCREEN_HEIGHT /2
    }
    public var txtInfo:Text = Text{
        x:10
        y:20
        wrappingWidth: Config.SCREEN_WIDTH - 20
        font: Font { size: 18 }
        fill: Color.WHITE
        content:"Game instructions will go here..."

    }
    public var gameBoard: Group = Group{
        content: [
            //background rectangle...
            Rectangle{
                width: Config.SCREEN_WIDTH;
                height: Config.SCREEN_HEIGHT;
                fill: Color.BLACK
            }
            //add the info text to the scene...
            txtInfo,
            //add the ship to the scene...
            ship
        ]
    }
    override public function create():Node{
        return gameBoard;
    }
}

 

Now we'll create a Ship class, which will render our ship on the game board. There's just one thing I want to point out before I show you the code.  When you place an image on the scene, it's top left corner will land on the X and Y coordinates that you specify.  But we need to determine the center point of the ship, which is why I created the offsetX and offsetY variables in the Ship class.  Using this method in the next lesson we will be able to rotate the ship so that it pivots from it's center point rather than it's top left corner.  Here's the code for Ship.fx:

 

package blasteroids;

import javafx.scene.CustomNode;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.Node;

public class Ship extends CustomNode {
    public var posX:Number = 0;
    public var posY:Number = 0;
    public var offsetX:Number = bind posX - img.width/2;
    public var offsetY:Number = bind posY - img.height/2;

    var img = Image{
        url: "{__DIR__}ship.png"

        //there is a link to download this image below

        //just copy it to the same directory as your class files
    }

    var imgView = ImageView{
        image: img
        x: bind offsetX
        y: bind offsetY
    }

    override public function create():Node{
        return imgView
    }
}

 

That's it! We've got all the basics of our game in place.  In the next few lessons we'll be adding more and more features to our game. You might want to use your own image for the ship, or you can download the ship image that I used. IMPORTANT: Make sure you don't forget to include an image when you refer to one from your code.  I've noticed that it won't cause an error when you run or compile the project, so it may not be obvious when you're troubleshooting.

 

If you'd like to continue to the next lesson, where we start to move our ship around the game board, go to Programming Games in JavaFX - Part 2.

 

 

2 Comments - Average Rating:5

Comments:
superb so far.. hope it continues like this further..
ita amazing!!!
Rating: 5
Date Posted: June 4th, 2010


Grate tutorial been looking for something like this for ages and its very nice game cant wait to read more.

Lee
Rating: 5
Date Posted: October 30th, 2009



RECENT ARTICLES