App Engine 1.6.5 Released

April showers — and
a bit more than showers — have kept us happily inside working away on our fourth release of this year (we are really looking forward to those flowers). Today’s release includes some updates to the Datastore and the runtimes, new features for the Images API, and more!


We’ve introduced an experimental type of query,
projection queries, in the Datastore. For the SQL fans amongst us, this is similar to queries of the form:

SELECT Property1, Property2 FROM MyEntity ORDER BY Property3

Projection queries have the same cost and performance characteristics as keys-only queries but return entity objects populated only with the requested properties.

We are also adding several other Datastore features in this release:

  • Each entity group now has a numeric version property that strictly increases on every entity group change. You can use this counter, for example, to easily and consistently cache the results of an ancestor query, such as the count of all entities in an entity group (Java®, Python examples).
  • The Datastore Admin now allows you to restore individual Kinds from an existing backup, abort in-progress backups, and view more detailed backup and restore information.
  • For Python users, the @db.transactional decorator now supports concurrent transactions. We’ve also expanded the options available for the db.run_in_transtion_options() function.

Images API

  • The Images API can now access image objects stored in Google Cloud Storage.
  • The URLs generated by get_serving_url()/getServingUrl() that make use of our high-speed image serving infrastructure can now be generated to serve over HTTPS.

Task Queue

We are looking for Trusted Testers for Task Queue Statistics. Task Queue Statistics allows you to fetch statistics and information about your task queue from within your application.
Apply now to be a Trusted Tester.

Request Headers

In this release, we are including additional
request headers to provide more detailed information about the origin of a request. We’ve added
Region, City and LatLng headers to each request where this information can be inferred from the IP address.


Finally, an important piece of news for our Java developers: the <threadsafe> element is now required in appengine-web.xml file; omitting it will cause an error in the dev appserver.

As always, send us feedback in our Google Group, send us technical questions on Stack Overflow, and read the complete release notes for all the new features and fixes in this release for Java, Python, and Go.

Posted by the App Engine Team

Java is a registered trademark of Oracle and/or its affiliates.

Source :

JavaFX 2 GameTutorial Part 2


This is the second installment of a series of blog entries relating to a JavaFX 2 Game Tutorial. If you have not read Part 1 please see the
introduction section of the JavaFX 2 Game Tutorial. To recap in Part 1, I mention some aspects of game play and a simple demo of a prototype spaceship (comprised of simple shapes) that is capable of navigating via the mouse.
Disclaimer: This is a long tutorial so if you just want to run the demo just
Click HERE. The demo is called Atom Smasher where you generate atoms (spheres) that collide. You may freeze the game to add more atoms. The objective is to have more than one atom alive and bouncing around. A text displays the current number of atoms floating around. Before beginning our discussion on a game loop I wanted to give you some background history about games and animation.


Back in the day (during the 80s-90s) many game programmers attempted to animate images has encountered the infamous screen flicker problem. This is where your
sprites (graphic images) will often flash and make the game look quite awful. All monitors have a refresh rate where certain intervals the pixels will be redrawn (called
vertical retrace CRTs). For example, if the refresh rate is 80 Hz it is approximately 80 times a second the screen is redrawn. If you are modifying things on the screen you can often be out ofsyncbecause of being in the middle of a refresh interval. What should you do about this? Well, actually there are two things that will help remedy this problem (double buffering & knowing when the cycle is occurring). Some clever developers created a technique called double buffering.
Double buffering is a technique which consists of two surfaces where each takes turns on becoming the displayable surface and the other is an offscreen area (buffer surface). This technique is really a digital sleight of hand trick where the developer can pre calculate the sprites and their positions to be drawn on the offscreen surface. Once you are finished drawing on the offscreen buffer the code will switch it as the displayable surface. An important thing to point out is that we still have an issue due to the fact that we need to be notified when the refresh interval is about to begin the redraw process. In Java this ability is built in via the
BufferStrategy API. So, where am I going with this? Sometimes explaining the past strategies will help us appreciate what we have today. Do we need to do this in JavaFX? Nope. Have no fear JavaFX is here! All of the issues thatI’vementioned are all taken care of for us by using JavaFX’s Scene graph API. However, most games will still use the old fashion way of animating graphics and updating the game world called the ‘
Game Loop’.

The Game Loop

Simply put the game loop is responsible for updating sprites (graphics), checking collision, and cleanup. Older game loops will check for key and mouse events as part of the loop. Since JavaFX abstracts events to allow the Scene or individual nodes to handle events the ability to listen to low level events aren’t necessary in our game loop. Shown below is a source code snippet of a typical game loop which will update sprites, check collisions, and cleanup sprites at each cycle. You will notice the
Duration object from JavaFX 2.x which represents 60 divided by 1000 milliseconds or 60 frames per second(FPS). Each frame will call the
handle() method of the JavaFX’s
EventHandler interface in order to update the game world. Hypothetically, I’ve create three methods
checkCollisions(), and
cleanupSprites() that will be invoked to handle sprites in the game.

   final Duration oneFrameAmt = Duration.millis(1000/60);   final KeyFrame oneFrame = new KeyFrame(oneFrameAmt,      new EventHandler() {      @Override      public void handle(javafx.event.ActionEvent event) {         // update actors         updateSprites();         // check for collision         checkCollisions();         // removed dead things         cleanupSprites();      }   }); // oneFrame   // sets the game world's game loop (Timeline)   TimelineBuilder.create()      .cycleCount(Animation.INDEFINITE)      .keyFrames(oneFrame)      .build()      .play();

The above code snippet is really all you need to create a simple game or animation. However, you may want to take things to the next level. You may want to create a game engine that can manage sprites and the state of the game world.

Game Engine

game engine is a fancy name for a utility or library responsible for encapsulating the game world, running the game loop, managing sprites, physics, etc. This is essentially a small game framework that allows you to extend or reuse so you don’t have to reinvent the wheel when creating a 2D game from scratch. To fast forward I created a UML class diagram of a design of a game engine.

Shown below is Figure 1 A JavaFX Game Engine Class diagram.

Figure 1. A JavaFX 2 Game Engine Design

In Figure 1 A JavaFX 2 Game Engine Design you will notice three classes a
SpriteManager, and
Sprite. The
GameWorld class is responsible for initializing the game state, executing the game loop, updating sprites, handling sprite collisions, and cleaning up. Next is the
SpriteManager class which in charge of managing sprites by adding, removing, and other house keeping for collisions. Lastly, is the
Sprite class which is responsible for maintaining the state of an image (Actor). In a 2D world a sprite can contain the object’s velocity, rotation, scene node or image that eventually gets rendered at each cycle (key frame/frames per second).

Just a quick reminder on UML notation:

  • Plus symbol ‘+‘ denotes that a class member is public.
  • Minus symbol ‘‘ denotes that a class member isprivate
  • Hash symbol ‘#‘ denotes that a class member is protected.


Below is the source code implementation of the GameWorld class. Click to expand. Later you will see a class diagram depicting a simple demo game that will extend the GameWorld class (see AtomSmasher).

package carlfx.gameengine;import javafx.animation.Animation;import javafx.animation.KeyFrame;import javafx.animation.Timeline;import javafx.animation.TimelineBuilder;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Group;import javafx.scene.Scene;import javafx.stage.Stage;import javafx.util.Duration;/** * This application demonstrates a JavaFX 2.x Game Loop. * Shown below are the methods which comprise of the fundamentals to a * simple game loop in JavaFX:* *  <strong>initialize()</strong> - Initialize the game world. *  <strong>beginGameLoop()</strong> - Creates a JavaFX Timeline object containing the game life cycle. *  <strong>updateSprites()</strong> - Updates the sprite objects each period (per frame) *  <strong>checkCollisions()</strong> - Method will determine objects that collide with each other. *  <strong>cleanupSprites()</strong> - Any sprite objects needing to be removed from play. * * @author cdea */public abstract class GameWorld {    /** The JavaFX Scene as the game surface */    private Scene gameSurface;    /** All nodes to be displayed in the game window. */    private Group sceneNodes;    /** The game loop using JavaFX's <code>Timeline</code> API.*/    private static Timeline gameLoop;    /** Number of frames per second. */    private final int framesPerSecond;    /** Title in the application window.*/    private final String windowTitle;    /**     * The sprite manager.     */    private final SpriteManager spriteManager = new SpriteManager();    /**     * Constructor that is called by the derived class. This will     * set the frames per second, title, and setup the game loop.     * @param fps - Frames per second.     * @param title - Title of the application window.     */    public GameWorld(final int fps, final String title) {        framesPerSecond = fps;        windowTitle = title;        // create and set timeline for the game loop        buildAndSetGameLoop();    }    /**     * Builds and sets the game loop ready to be started.     */    protected final void buildAndSetGameLoop() {        final Duration oneFrameAmt = Duration.millis(1000/getFramesPerSecond());        final KeyFrame oneFrame = new KeyFrame(oneFrameAmt,            new EventHandler() {                @Override                public void handle(javafx.event.ActionEvent event) {                    // update actors                    updateSprites();                    // check for collision                    checkCollisions();                    // removed dead things                    cleanupSprites();                }        }); // oneFrame        // sets the game world's game loop (Timeline)        setGameLoop(TimelineBuilder.create()                .cycleCount(Animation.INDEFINITE)                .keyFrames(oneFrame)                .build());    }    /**     * Initialize the game world by update the JavaFX Stage.     * @param primaryStage     */    public abstract void initialize(final Stage primaryStage);    /**Kicks off (plays) the Timeline objects containing one key frame     * that simply runs indefinitely with each frame invoking a method     * to update sprite objects, check for collisions, and cleanup sprite     * objects.     *     */    public void beginGameLoop() {        getGameLoop().play();    }    /**     * Updates each game sprite in the game world. This method will     * loop through each sprite and passing it to the handleUpdate()     * method. The derived class should override handleUpdate() method.     *     */    protected void updateSprites() {        for (Sprite sprite:spriteManager.getAllSprites()){            handleUpdate(sprite);        }    }    /** Updates the sprite object's information to position on the game surface.     * @param sprite - The sprite to update.     */    protected void handleUpdate(Sprite sprite) {    }    /**     * Checks each game sprite in the game world to determine a collision     * occurred. The method will loop through each sprite and     * passing it to the handleCollision()     * method. The derived class should override handleCollision() method.     *     */    protected void checkCollisions() {        // check other sprite's collisions        spriteManager.resetCollisionsToCheck();        // check each sprite against other sprite objects.        for (Sprite spriteA:spriteManager.getCollisionsToCheck()){            for (Sprite spriteB:spriteManager.getAllSprites()){                if (handleCollision(spriteA, spriteB)) {                    // The break helps optimize the collisions                    //  The break statement means one object only hits another                    // object as opposed to one hitting many objects.                    // To be more accurate comment out the break statement.                    break;                }            }        }    }    /**     * When two objects collide this method can handle the passed in sprite     * objects. By default it returns false, meaning the objects do not     * collide.     * @param spriteA - called from checkCollision() method to be compared.     * @param spriteB - called from checkCollision() method to be compared.     * @return boolean True if the objects collided, otherwise false.     */    protected boolean handleCollision(Sprite spriteA, Sprite spriteB) {        return false;    }    /**     * Sprites to be cleaned up.     */    protected void cleanupSprites() {        spriteManager.cleanupSprites();    }    /**     * Returns the frames per second.     * @return int The frames per second.     */    protected int getFramesPerSecond() {        return framesPerSecond;    }    /**     * Returns the game's window title.     * @return String The game's window title.     */    public String getWindowTitle() {        return windowTitle;    }    /**     * The game loop (Timeline) which is used to update, check collisions, and     * cleanup sprite objects at every interval (fps).     * @return Timeline An animation running indefinitely representing the game     * loop.     */    protected static Timeline getGameLoop() {        return gameLoop;    }    /**     * The sets the current game loop for this game world.     * @param gameLoop Timeline object of an animation running indefinitely     * representing the game loop.     */    protected static void setGameLoop(Timeline gameLoop) {        GameWorld.gameLoop = gameLoop;    }    /**     * Returns the sprite manager containing the sprite objects to     * manipulate in the game.     * @return SpriteManager The sprite manager.     */    protected SpriteManager getSpriteManager() {        return spriteManager;    }    /**     * Returns the JavaFX Scene. This is called the game surface to     * allow the developer to add JavaFX Node objects onto the Scene.     * @return     */    public Scene getGameSurface() {        return gameSurface;    }    /**     * Sets the JavaFX Scene. This is called the game surface to     * allow the developer to add JavaFX Node objects onto the Scene.     * @param gameSurface The main game surface (JavaFX Scene).     */    protected void setGameSurface(Scene gameSurface) {        this.gameSurface = gameSurface;    }    /**     * All JavaFX nodes which are rendered onto the game surface(Scene) is     * a JavaFX Group object.     * @return Group The root containing many child nodes to be displayed into     * the Scene area.     */    public Group getSceneNodes() {        return sceneNodes;    }    /**     * Sets the JavaFX Group that will hold all JavaFX nodes which are rendered     * onto the game surface(Scene) is a JavaFX Group object.     * @param sceneNodes The root container having many children nodes     * to be displayed into the Scene area.     */    protected void setSceneNodes(Group sceneNodes) {        this.sceneNodes = sceneNodes;    }}


A sprite manager class is a helper class to assist the game loop to keep track of sprites. Normally a sprite manager will contain all sprites and each sprite contains a JavaFX Node that is displayed onto the Scene graph.

Shown below is the source code. Click to expand.

package carlfx.gameengine;import java.util.*;/** * Sprite manager is responsible for holding all sprite objects, and cleaning up * sprite objects to be removed. All collections are used by the JavaFX * application thread. During each cycle (animation frame) sprite management * occurs. This assists the user of the API to not have to create lists to * later be garbage collected. Should provide some performance gain. * @author cdea */public class SpriteManager {    /** All the sprite objects currently in play */    private final static List GAME_ACTORS = new ArrayList<>();    /** A global single threaded list used to check collision against other     * sprite objects.     */    private final static List CHECK_COLLISION_LIST = new ArrayList<>();    /** A global single threaded set used to cleanup or remove sprite objects     * in play.     */    private final static Set CLEAN_UP_SPRITES = new HashSet<>();    /** */    public List getAllSprites() {        return GAME_ACTORS;    }    /**     * VarArgs of sprite objects to be added to the game.     * @param sprites     */    public void addSprites(Sprite... sprites) {        GAME_ACTORS.addAll(Arrays.asList(sprites));    }    /**     * VarArgs of sprite objects to be removed from the game.     * @param sprites     */    public void removeSprites(Sprite... sprites) {        GAME_ACTORS.removeAll(Arrays.asList(sprites));    }    /** Returns a set of sprite objects to be removed from the GAME_ACTORS.     * @return CLEAN_UP_SPRITES     */    public Set getSpritesToBeRemoved() {        return CLEAN_UP_SPRITES;    } /**     * Adds sprite objects to be removed     * @param sprites varargs of sprite objects.     */    public void addSpritesToBeRemoved(Sprite... sprites) {        if (sprites.length > 1) {            CLEAN_UP_SPRITES.addAll(Arrays.asList((Sprite[]) sprites));        } else {            CLEAN_UP_SPRITES.add(sprites[0]);        }    }    /**     * Returns a list of sprite objects to assist in collision checks.     * This is a temporary and is a copy of all current sprite objects     * (copy of GAME_ACTORS).     * @return CHECK_COLLISION_LIST     */    public List getCollisionsToCheck() {        return CHECK_COLLISION_LIST;    }    /**     * Clears the list of sprite objects in the collision check collection     * (CHECK_COLLISION_LIST).     */    public void resetCollisionsToCheck() {        CHECK_COLLISION_LIST.clear();        CHECK_COLLISION_LIST.addAll(GAME_ACTORS);    }    /**     * Removes sprite objects and nodes from all     * temporary collections such as:     * CLEAN_UP_SPRITES.     * The sprite to be removed will also be removed from the     * list of all sprite objects called (GAME_ACTORS).     */    public void cleanupSprites() {        // remove from actors list        GAME_ACTORS.removeAll(CLEAN_UP_SPRITES);        // reset the clean up sprites        CLEAN_UP_SPRITES.clear();    }}


The Sprite class represents an image or node to be displayed onto the JavaFX Scene graph. In a 2D game a sprite will contain additional information such as its velocity for the object as it moves across the scene area. The game loop will call the update() and collide() method at every interval of a key frame.

Shown below is the source code. Click to expand.

package carlfx.gameengine;import java.util.ArrayList;import java.util.List;import javafx.animation.Animation;import javafx.scene.Node;/** * The Sprite class represents a image or node to be displayed. * In a 2D game a sprite will contain a velocity for the image to * move across the scene area. The game loop will call the update() * and collide() method at every interval of a key frame. A list of * animations can be used during different situations in the game * such as rocket thrusters, walking, jumping, etc. * @author cdea */public abstract class Sprite {    /** Animation for the node */    public List animations = new ArrayList<>();    /** Current display node */    public Node node;    /** velocity vector x direction */    public double vX = 0;    /** velocity vector y direction */    public double vY = 0;    /** dead? */    public boolean isDead = false;    /**     * Updates this sprite object's velocity, or animations.     */    public abstract void update();    /**     * Did this sprite collide into the other sprite?     *     * @param other - The other sprite.     * @return     */    public boolean collide(Sprite other) {        return false;    }}

JavaFX 2 Game Loop Demo – Atom Smasher

Whew! If you’ve got this far you are one brave soul. Let’s take a small break and try out the demo I created using the game engine above.

Shown below is a Java Webstart button to launch the game demo. Later, you will see the design and source code detailing how it was created.


  • Java 7 or later
  • JavaFX

    2.1 or later
  • Windows XP or later (Should be available soon for Linux/MacOS)
AtomSmasher Game loop demo

GameLoopPart2 Design

Below is a class diagram of the game demo called Atom Smasher which uses the game engine framework mentioned earlier.

Shown below is Figure 2 Atom Smasher Class Diagram.

Figure 2. Atom Smasher Class Diagram


The GameLoopPart2 is the driver or main JavaFX application that runs the game. This creates a GameWorld object to be initialized and starts the game loop.

Shown below is the source code. Click to expand.

package carlfx;import carlfx.gameengine.GameWorld;import javafx.application.Application;import javafx.stage.Stage;/** * The main driver of the game. * @author cdea */public class GameLoopPart2 extends Application {    GameWorld gameWorld = new AtomSmasher(60, "JavaFX 2 GameTutorial Part 2 - Game Loop");    /**     * @param args the command line arguments     */    public static void main(String[] args) {        launch(args);    }    @Override    public void start(Stage primaryStage) {        // setup title, scene, stats, controls, and actors.        gameWorld.initialize(primaryStage);        // kick off the game loop        gameWorld.beginGameLoop();        // display window;    }}


AtomSmasher is a derived class of the GameWorld class. It creates many spheres that animate with random velocities, colors and positions. Button controls lets the user generate more ‘atoms’ (JavaFX Circle nodes). As each atom collides with one another they will invoke the implode() method that produces a fade transition animation. You will notice how easy it is to implement this game by simply implementing
initialize(), handleUpdate(), handleCollision(), and
cleanupSprites() methods. Once implemented the game engine does the rest. The
initialize() method creates the button controls for the user. To update the sprites positions or change the game state you will implement the
handleUpdate() method. To compare all sprites if they have collided with one another you will implement the
handleCollision(). The last part of the game loop’s life cycle is cleaning up sprites. Cleaning up means updating the sprite manger and updating the JavaFX Scene (removing nodes).

Shown below is the source code. Click to expand.

package carlfx;import carlfx.gameengine.GameWorld;import carlfx.gameengine.Sprite;import java.util.Random;import javafx.animation.Timeline;import javafx.event.EventHandler;import javafx.scene.Group;import javafx.scene.Scene;import javafx.scene.control.ButtonBuilder;import javafx.scene.control.Label;import javafx.scene.input.MouseEvent;import javafx.scene.layout.HBoxBuilder;import javafx.scene.layout.VBox;import javafx.scene.layout.VBoxBuilder;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.stage.Stage;import static javafx.animation.Animation.Status.RUNNING;import static javafx.animation.Animation.Status.STOPPED;/** * This is a simple game world simulating a bunch of spheres looking * like atomic particles colliding with each other. When the game loop begins * the user will notice random spheres (atomic particles) floating and * colliding. The user is able to press a button to generate more * atomic particles. Also, the user can freeze the game. * * @author cdea */public class AtomSmasher extends GameWorld {    /** Read only field to show the number of sprite objects are on the field*/    private final static Label NUM_SPRITES_FIELD = new Label();    public AtomSmasher(int fps, String title){        super(fps, title);    }    /**     * Initialize the game world by adding sprite objects.     * @param primaryStage     */    @Override    public void initialize(final Stage primaryStage) {        // Sets the window title        primaryStage.setTitle(getWindowTitle());        // Create the scene        setSceneNodes(new Group());        setGameSurface(new Scene(getSceneNodes(), 640, 580));        primaryStage.setScene(getGameSurface());        // Create many spheres        generateManySpheres(150);        // Display the number of spheres visible.        // Create a button to add more spheres.        // Create a button to freeze the game loop.        final Timeline gameLoop = getGameLoop();        VBox stats = VBoxBuilder.create()            .spacing(5)            .translateX(10)            .translateY(10)            .children(HBoxBuilder.create()                .spacing(5)                .children(new Label("Number of Particles: "), // show no. particles                    NUM_SPRITES_FIELD).build(),                    // button to build more spheres                    ButtonBuilder.create()                        .text("Regenerate")                        .onMousePressed(new EventHandler() {                            @Override                            public void handle(MouseEvent arg0) {                                generateManySpheres(150);                            }}).build(),                    // button to freeze game loop                    ButtonBuilder.create()                        .text("Freeze/Resume")                        .onMousePressed(new EventHandler() {                            @Override                            public void handle(MouseEvent arg0) {                                switch (gameLoop.getStatus()) {                                    case RUNNING:                                        gameLoop.stop();                                        break;                                    case STOPPED:                              ;                                        break;                                }                            }}).build()            ).build(); // (VBox) stats on children        // lay down the controls        getSceneNodes().getChildren().add(stats);    }    /**     * Make some more space spheres (Atomic particles)     */    private void generateManySpheres(int numSpheres) {        Random rnd = new Random();        Scene gameSurface = getGameSurface();        for (int i=0; i (gameSurface.getWidth() - (circle.getRadius() * 2))) {                newX = gameSurface.getWidth() - (circle.getRadius()  * 2);            }            // check for the bottom of screen the height newY is greater than height            // minus radius times 2(height of sprite)            double newY = rnd.nextInt((int) gameSurface.getHeight());            if (newY > (gameSurface.getHeight() - (circle.getRadius() * 2))) {                newY = gameSurface.getHeight() - (circle.getRadius() * 2);            }            circle.setTranslateX(newX);            circle.setTranslateY(newY);            circle.setVisible(true);            circle.setId(b.toString());            // add to actors in play (sprite objects)            getSpriteManager().addSprites(b);            // add sprite's            getSceneNodes().getChildren().add(0, b.node);        }    }    /**     * Each sprite will update it's velocity and bounce off wall borders.     * @param sprite - An atomic particle (a sphere).     */    @Override    protected void handleUpdate(Sprite sprite) {        if (sprite instanceof Atom) {            Atom sphere = (Atom) sprite;            // advance the spheres velocity            sphere.update();            // bounce off the walls when outside of boundaries            if (sphere.node.getTranslateX() > (getGameSurface().getWidth()  -                sphere.node.getBoundsInParent().getWidth()) ||                sphere.node.getTranslateX() < 0 ) {                 sphere.vX = sphere.vX * -1;             }             if (sphere.node.getTranslateY() > getGameSurface().getHeight()-                sphere.node.getBoundsInParent().getHeight() ||                sphere.node.getTranslateY() < 0) {                sphere.vY = sphere.vY * -1;            }        }    }    /**     * How to handle the collision of two sprite objects. Stops the particle     * by zeroing out the velocity if a collision occurred.     * @param spriteA     * @param spriteB     * @return     */    @Override    protected boolean handleCollision(Sprite spriteA, Sprite spriteB) {        if (spriteA.collide(spriteB)) {            ((Atom)spriteA).implode(this);            ((Atom)spriteB).implode(this);            getSpriteManager().addSpritesToBeRemoved(spriteA, spriteB);            return true;        }        return false;    }    /**     * Remove dead things.     */    @Override    protected void cleanupSprites() {        // removes from the scene and backend store        super.cleanupSprites();        // let user know how many sprites are showing.        NUM_SPRITES_FIELD.setText(String.valueOf(getSpriteManager().getAllSprites().size()));    }}


The Atom class extends from the Sprite class. An atom is a sprite that appears like a spherical object that moves across the scene. An atom will have a random radius, color, and velocity. As each atom sprite collides with another atom they will animate a fade transition (the implode() method).

Shown below is the source code. Click to expand.

package carlfx;import carlfx.gameengine.GameWorld;import carlfx.gameengine.Sprite;import javafx.animation.FadeTransitionBuilder;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.paint.Color;import javafx.scene.paint.RadialGradient;import javafx.scene.paint.RadialGradientBuilder;import javafx.scene.paint.Stop;import javafx.scene.shape.Circle;import javafx.scene.shape.CircleBuilder;import javafx.util.Duration;/** * A spherical looking object (Atom) with a random radius, color, and velocity. * When two atoms collide each will fade and become removed from the scene. The * method called implode() implements a fade transition effect. * * @author cdea */public class Atom extends Sprite {    public Atom(double radius, Color fill) {        Circle sphere = CircleBuilder.create()                .centerX(radius)                .centerY(radius)                .radius(radius)                .cache(true)                .build();        RadialGradient rgrad = RadialGradientBuilder.create()                    .centerX(sphere.getCenterX() - sphere.getRadius() / 3)                    .centerY(sphere.getCenterY() - sphere.getRadius() / 3)                    .radius(sphere.getRadius())                    .proportional(false)                    .stops(new Stop(0.0, fill), new Stop(1.0, Color.BLACK))                    .build();        sphere.setFill(rgrad);        // set javafx node to a circle        node = sphere;    }    /**     * Change the velocity of the atom particle.     */    @Override    public void update() {        node.setTranslateX(node.getTranslateX() + vX);        node.setTranslateY(node.getTranslateY() + vY);    }    @Override    public boolean collide(Sprite other) {        if (other instanceof Atom) {            return collide((Atom)other);        }       return false;    }    /**     * When encountering another Atom to determine if they collided.     * @param other Another atom     * @return boolean true if this atom and other atom has collided,     * otherwise false.     */    private boolean collide(Atom other) {        // if an object is hidden they didn't collide.        if (!node.isVisible() ||            !other.node.isVisible() ||            this == other) {            return false;        }        // determine it's size        Circle otherSphere = other.getAsCircle();        Circle thisSphere =  getAsCircle();        double dx = otherSphere.getTranslateX() - thisSphere.getTranslateX();        double dy = otherSphere.getTranslateY() - thisSphere.getTranslateY();        double distance = Math.sqrt( dx * dx + dy * dy );        double minDist  = otherSphere.getRadius() + thisSphere.getRadius() + 3;        return (distance < minDist);    }    /**     * Returns a node casted as a JavaFX Circle shape.     * @return Circle shape representing JavaFX node for convenience.     */    public Circle getAsCircle() {        return (Circle) node;    }    /**     * Animate an implosion. Once done remove from the game world     * @param gameWorld - game world     */    public void implode(final GameWorld gameWorld) {        vX = vY = 0;        FadeTransitionBuilder.create()            .node(node)            .duration(Duration.millis(300))            .fromValue(node.getOpacity())            .toValue(0)            .onFinished(new EventHandler() {                @Override                public void handle(ActionEvent arg0) {                    isDead = true;                    gameWorld.getSceneNodes().getChildren().remove(node);                }            })            .build()            .play();    }}


Hopefully you’ve got a chance to understand the fundamentals of a gaming loop and later apply the knowledge by implementing a robust game engine. Although, I briefly mention collision I am saving that for Part 4 of these tutorials. Please stay tuned for Part 3 where we will get into input using the keyboard or mouse. Feel free to experiment. Let me know what you come up with.

To obtain the source code please download the link to a jar file below by using the ‘
Save link As‘ option in your browser. If you are on a Windows system you can change the extension from ‘
jar‘ to ‘
zip‘ to be easily expanded. It will contain a directory ‘
src‘ with the source code.

The source code location:

The published version of the source code is at the
GitHub called(
JFXGen)for you to clone and fork to your hearts content (It’s there for you to use for your own projects). Enjoy.


JavaFX 2 GameTutorial Part 2 from our
JCG partner Carl Dea at the
Carl’s FX Blog blog.

Source :



It is love at first type. I fell in deep love with it from the first moment I used it. Didn’t you? How many times have we used it till now? It is one of the most number of times compiled statement in the history of java. We fondly call it SOP. If you want to dive directly to topic, jump to the first heading.

I first learnt DBase III+ and the statement to print is ? "Hello World". Then I went on to to study umpteen number of languages courtesy a poorly planned curriculum. Instead, we should have spent more time on flip-flops.

At the end of this article I have summarized Pascal, C, C++, Lisp, Prolog, Cobol, Basic, Fortran – I studied all these in a 3 year post graduate program and more than that. As I told, I am still not sure of the difference it made. Learning multiple languages is good, but my humble opinion is, do it after spending more time on fundamentals like data structures, algorithms, discrete maths, computer architecture, etc. Okay, where did I left? Lets continue with our System.out.println for now.

What is System.out.println

System.out.println prints the argument passed, into the System.out which is generally stdout.

  • System – is a final class and cannot be instantiated. Therefore all its memebers (fields and methods) will be static and we understand that it is an utility class. As per javadoc, “…Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array…”
  • out – is a static member field of System class and is of type PrintStream. Its access specifiers are public final. This gets instantiated during startup and gets mapped with standard output console of the host. This stream is open by itself immediately after its instantiation and ready to accept data. When running a program from windows command line, it is the standard console.
  • println – println prints the argument passed to the standard console and a newline. There are multiple println methods with different arguments (overloading). Every println makes a call to print method and adds a newline. print calls write() and the story goes on like that.

Change out of System.out.println

‘out’ object can be customized. out gets initialized by java runtime environment at startup and it can be changed by developer during execution. Instead of standard output, in default cases when you run a program through command line, the output is printing in the same command window. We can change that behavior using setOut method as below. In the following example, I have redirected the output to a text file in the same directory.

public class ChangeOut {	public static void main(String args[]) {		try {			System.setOut(new PrintStream(new FileOutputStream("log.txt")));			System.out.println("Now the output is redirected!");		} catch(Exception e) {}	}}

System.out.println vs loggers like Log4j

Log4J has mulitple levels for logging. If we are writing a real short program, just for experimental/learning purposes SOPs are fine. When we are developing a production quality software project, we should be aware that a professional logger should be used and SOPs should be avoided. Why?

  • Flexibility: a professional logger like log4j provides different levels for logging. We can seggregate the log message accordingly. For example, X messages should be printed only on PRODUCTION, Y messages should be printed on ERROR, etc.
  • Configurability: in just one parameter change we can switch off all the logging statements.
  • Maintainability: imagine if we have hundreds of SOPs littered all through the application, it would be difficult to maintain the program over a period.
  • Granularity: In an application, every single class can have a different logger and controlled accordingly.
  • Utility: Option for redirecting the message is limited in System.out, but in case of a logger you have appenders which provides numerous options. We can even create a custom ouput option and redirect it to that.

Having said all the above, we still use System.out.println for logging and debugging. Which should be strictly avoided. This is driven by (bad)habit. I want to share how a habit became a convention. In this case its a good habit. Its using ‘i’, ‘j’ as index in for-loop. In FORTRAN language, we need not declare integer variables. Variable names that start with i, j, k, l, m and n are integer variables. So, FORTRAN developers named for-loop index with i,j,k and that habit carried on to other languages. Just a habit and became a good convention!

System.out.println and Performance

There is a general notion that SOPs are bad in performance. When we analyze deeply, the sequence of calls are like println -> print -> write() + newLine(). This sequence flow is an implementation of Sun/Oracle JDK. Both write() and newLine() contains a synchronized block. Synchronization has a little overhead, but more than that the cost of adding characters to the buffer and printing is high.

When we run a performance analysis, run multiple number of SOP and record the time, the execution duration increases proportionally. Performance degrades when we print more that 50 characters and print more than 50,000 lines.

It all depends on the scenario we use it. Whatever may be the case, do not use System.out.println for logging to stdout.

Static Import to Shorten SOP

Someone complained that System.out.println is a loooong statement to print something. static import may shorten it a bit but it is not recommended, because it results in poor readability. I am just using this situation to explain static import and avoid using it in the below scenario.

import static java.lang.System.out;public class ShortSOP {public static void main(String[] args) {out.println("Hello, world");}}

In Eclipse you have programmed shortcuts like ctrl + spac to help you out.

System.err and

As a related section, I wish to discuss about ‘err’ and ‘in’. ‘in’ is associated with InputStream. Opposite to ‘out’, ‘in’ is used to get input from standard console generally keyboard.
‘err’ is associated with PrintStream and prints the argument to the standard error output stream. When you use eclipse kind of IDE you can see the differene in ouput between ‘out’ and ‘err’.

public class InOutErr {public static void main(String args[]) {try {BufferedReader reader = new BufferedReader(;String filename = reader.readLine();  InputStream input = new FileInputStream(filename);  System.out.println("File opened...");} catch (IOException e){  System.err.println("Where is that file?");}}}

Print in other languages

? "Hello World"


 #include <stdio.h> #include <stdlib.h> int main(void) {  printf("Hello, world");  return EXIT_SUCCESS; }


 #include <iostream> int main() { 	std::cout << "Hello, World." << std::endl; }










go :-	writeln('Hello World').

Yes, I sourced all this programs from Internet 🙂 How come you expect me to remember all these! System.out.println(“Bye”);

Source :