Posts Tagged ‘Java’

Differences between TopLink and EclipseLink

Monday, March 22nd, 2010

The default persistence manager in Netbeans Release 6.8 has changed from TopLink to EclipseLink and I will list error messages and differences that I find as I go along.

1.
ErrorMessage

Exception [EclipseLink-8034] (Eclipse Persistence Services - 2.0.0.v20091127-r5931): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Error compiling the query [findUserByEmail: SELECT u FROM theuser u WHERE u.email = :email]. Unknown entity type [theuser].
at org.eclipse.persistence.exceptions.JPQLException.entityTypeNotFound(JPQLException.java:483)

Solution
EclipseLink is case sensitive. If your entity is named “TheUser” (yes, it is a dumm name for an entity) your named query should be:
@NamedQueries({
@NamedQuery(
name="findUserByEmail",
query="SELECT u FROM TheUser u WHERE u.email = :email"
)
})

and not ...SELECT u FROM theuser....

Creating a Simple Game in JavaFX (Part 4)

Wednesday, October 21st, 2009


In the previous entries we decided how our game should behave, we created the playing field and the player object. We now want to add the “enemy” objects to our game.

Creating the enemy objects

So far most of our game has been programmed in one file. For our enemies we will create a separate file and class named Enemy.fx


package myballgame;

import ...

public static def DEFAULT_FILL = Color.CRIMSON;

public class Enemy extends CustomNode {

    var radius = 10;
    var moveUp = false;
    var moveLeft = false;
    var speedX = 0;
    var speedY = 0;

    var enemy:Circle;

    override function create():Node {

        // Enemy Speed
        speedX = calcSpeed();
        speedY = calcSpeed();

        // Enemy initial Direction
        moveUp = calcRandomBoolean();
        moveLeft = calcRandomBoolean();

        // Enemy figure
        enemy = Circle {
            radius: radius
            fill: Color.CRIMSON
        }
        return enemy
    }

    function calcSpeed():Integer {
       var r = javafx.util.Math.random();
       if (r>0.66){
            return 3
        } else if (r<0.33) {
            return 2
        } else {
            return 1
        }
    }

    function calcRandomBoolean():Boolean {
        if (javafx.util.Math.random()>0.5)
            return true
        else
            return false
    }

    public function calcPosition(xMin:Integer,xMax:Integer,yMin:Integer,yMax:Integer) {
        if (moveUp) {
            var newY= translateY - speedY;
            if (newY > yMin + radius)
                translateY = newY
            else
                moveUp = false
        } else {
            var newY= translateY + speedY;
            if (newY < yMax - radius)
                translateY = newY
            else
                moveUp = true
        }
        if (moveLeft) {
            var newX = translateX - speedX;
            if (newX > xMin + radius)
                translateX = newX
            else
                moveLeft = false
        } else {
            var newX = translateX + speedX;
            if (newX

This is a big chunk of code but we will walk through it slowly.
The package definition at the top shows that this file is in the same package as our Main.fx file.
We then define the default fill color of our enemies.
Our Enemy class extends CustomNode which allows us to easily create our own Node objects to add to our Scene.
The variables radius, moveUp, moveLeft speedX, speedY and enemy will be explained later on.
The function create() defined in CustomNode must be overriden. This is were we initialize our object. We setup a random speed for our enemy in the x-direction and a different random speed for the y-direction of our enemy. We then give the enemy an initial random direction by setting moveUp and moveLeft to a random value calculated in calcRandomBoolean(). Finally we return a Node object that defines the shape of our Enemy. In our case a simple circle with a radius defined by the initialization of the radius variable.
At the end of the class we define a function that lets us calculate the Enemies new position. calcPosition(...) takes the bounds of our playing field as parameters and makes sure the new Enemy object position is within these bounds. If it is not it switches the Enemies direction. For example if the Enemy object is about to leave the playing field at the top. calcPosition(...) changes moveUp to false and in the next cycle the Enemy object will be moving downward, until it hits the lower edge of the playing field and the y-direction is again reversed.

Displaying the enemy objects

Now that we have defined an Enemy class it is time to display our enemies. This is done with the following changes to Main.fx


var player ...

var enemies : Enemy[] = for (i in [0..3]) {
    var enemy:Enemy = Enemy {
        translateX : randomEnemyInitPosition(), translateY:randomEnemyInitPosition()
    }
    enemy
};

var timeline ...

function randomEnemyInitPosition():Integer {
    var r = javafx.util.Math.random();
    var r2 = javafx.util.Math.random();
    ((r  * 100)+(r2*100)) as Integer
}

Stage {
    ...
    scene: Scene {
        ...
        content: Group {
            ...
            content: [
                playingField,
                player,
                enemies
            ]
            ...
        }
    }
}

We define an variable of type Enemy Array and initialize it with four Enemy objects. Each enemy object gets a random position within a 100 x 100 pixel area of the playing field assigned.
We then add our Enemy Array to the contents of our Group object just like we added our playing field and player.
The result looks like the following:

img4

Animating the Enemies
Now we would like to animate our enemy objects. As with the player the new enemy position is calculated with every cycle in our game play and calling the recalculate enemy position method must therefore be located in our timeline code:


var timeline: Timeline = Timeline {
    ...
    keyFrames : [
        KeyFrame {
            ...
            action: function() {
                // Enemy
                for (enemy in enemies)
                 enemy.calcPosition(playingField.boundsInLocal.minX,
                             playingField.boundsInLocal.maxX,
                             playingField.boundsInLocal.minY,
                             playingField.boundsInLocal.maxY);
            ...

So with each cycle we call the calcPosition(...) function of each player object and each enemy knows how to calculate its new position as we have seen earlier when we discussed the calcPosition(...) function.

In the next part we will deal with calculating collisions.

Creating a Simple Game in JavaFX (Part 3)

Friday, October 16th, 2009


So far we have created a simple JavaFX application which sports a rectangle shape which will be our playing field. In this part we will now add the player object and the code that lets the user control its movement.

Creating the Player Object


var player: Circle = Circle {
    translateX: 250, translateY:250
    radius: 10
    fill: Color.BLACK
}
Stage {
...
    scene: Scene {
        ...
        content: Group {
            ...
            content: [
                playingField,
                player
            ]
        }
    }
}

I will not spend a lot of time commenting the code. The player object is a simple Circle shape variable defined like the playing field at script level, i.e. outside the Stage object. The player object is then added to the content of Scene’s Group object’s content after the playing field. Adding it after the playing field makes it appear on top of the playing field otherwise it would not be visible. The result looks like this:

img3

Adding User Interaction
In order to move the player object around we will have to listen to key events. If the user presses the left arrow key, we want the player object to move left, if he presses the right arrow key, the object should move right etc.. But listening to key events is not enough. Later when we have enemy ball objects and our playing field has bounds that cannot be crossed, several actions need to be synchronized at a certain interval level. We will call this a cycle in the game play. Creating such a cycle that checks everything that has happened (for example our Key Events) and recalculates all other events (for example collisions) is very easy with a JavaFX timeline.


var timeline: Timeline = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames : [
        KeyFrame {
            time : 30ms
            canSkip: false
            action: function() {
            }
        }
    ]
}

Stage {
...
}

// Start game
timeline.playFromStart();

We define a timeline object that runs indefinately. Our cycle is 30ms long, so every 30ms all the game’s calculations are made. Do not forget to start the timeline at the end of our script. The function defined as the keyframe’s action is where these calculations take place as we will see in a minute.

Now for capturing the key events:


...
var moveUp = false;
var moveDown = false;
var moveLeft = false;
var moveRight = false;
...
Stage {
    ...
    scene: Scene {
        ...
        content: Group {
            focusTraversable: true
            ...
            content: [
                playingField,
                player
            ]
            onKeyPressed : function (e: KeyEvent){
              if (e.code == KeyCode.VK_LEFT) {
                    moveLeft = true;
              }
              if (e.code == KeyCode.VK_RIGHT) {
                    moveRight = true;
              }
              if (e.code == KeyCode.VK_UP) {
                    moveUp = true;
              }
              if (e.code == KeyCode.VK_DOWN) {
                    moveDown = true;
              }
            }
            onKeyReleased : function (e: KeyEvent){
              if (e.code == KeyCode.VK_LEFT) {
                    moveLeft = false;
              }
              if (e.code == KeyCode.VK_RIGHT) {
                    moveRight = false;
              }
              if (e.code == KeyCode.VK_UP) {
                    moveUp = false;
              }
              if (e.code == KeyCode.VK_DOWN) {
                    moveDown = false;
              }
            }
        }
    }
}

There are several things to notice in the new code. First of all the main Group object is set to focusTraversable=true. Otherwise it would not capture any key events. Capturing key events is pretty self explanatory except for the fact that we are not moving anything but merely remembering that the ball should move. If we press the left arrow key. The variable moveLeft is set to true. In our cycle we will have to process this information as we will see in a minute. If we release the key the variable moveLeft is set to false and the player object should not move. In theory if you were fast enough at pressing and releasing the key, a cycle could miss a movement, but this practically not happen and is not relevant. Now lets process the movement in our timeline object.


def PLAYER_BALL_STEP = 4;
...
var timeline: Timeline = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames : [
        KeyFrame {
            time : 30ms
            canSkip: false
            action: function() {
                // Player
                if (moveRight) {
                    var newX = player.translateX + PLAYER_BALL_STEP;
                    if (newX < playingField.boundsInLocal.maxX - player.radius - playingField.strokeWidth) {
                        player.translateX = newX
                    }
                }
                if (moveLeft) {
                    var newX = player.translateX - PLAYER_BALL_STEP;
                    if (newX > playingField.boundsInLocal.minX + player.radius + playingField.strokeWidth) {
                        player.translateX = newX
                    }
                }
                if (moveUp) {
                    var newY= player.translateY - PLAYER_BALL_STEP;
                    if (newY > playingField.boundsInLocal.minY + player.radius + playingField.strokeWidth) {
                        player.translateY = newY
                    }
                }
                if (moveDown) {
                    var newY= player.translateY + PLAYER_BALL_STEP;
                    if (newY < playingField.boundsInLocal.maxY - player.radius - playingField.strokeWidth) {
                        player.translateY = newY
                    }
                }
            }
        }
    ]
}

At the top of the script we define a constant called PLAYER_BALL_STEP which will tell us, if the player has moved the ball in one direction, how many pixel it should travel each circle. At 30ms cycle time moving just 1 pixel makes the player object very slow. This is where you can speed up and slow down the speed of the player object by adjusting the value. In a later game design you might add a speed up bonus or something similar.
Lets pretend the player has pressed the right arrow key. Variable moveRight is set to true, a new position on the x-axis is calculated for the player object by taking the current x position player.translateX and adding the number of steps the player object should move. We then check if the ball is within the bounds of the playing field, otherwise you could move the ball anywhere you wanted including right out of the window. If it is inbounds we set the X-axis position of our player object to the new value.
One thing to notice is that we are not working with if-else constructs. This is because in theory the user can press up and right at the same time and we then want the ball to move diagonally.
We now have a player object capable of moving and staying in the playing fields bounds. The next step is to add some enemy objects. Below is a complete listing of the code so far, so you don’t get mixed up.


/*
 * Main.fx
 *
 * Created on 15.10.2009, 17:36:19
 */

package myballgame;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.Group;

import javafx.scene.shape.Rectangle;

import javafx.scene.shape.Circle;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;

import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

/**
 * @author Alexander Gnodtke
 */
def PLAYER_BALL_STEP = 4;

var moveUp = false;
var moveDown = false;
var moveLeft = false;
var moveRight = false;

var playingField: Rectangle = Rectangle {
    arcWidth: 20  arcHeight: 20
    width: 280, height: 380
    fill: Color.ANTIQUEWHITE
    stroke: Color.DARKORANGE
    strokeWidth: 3
}

var player: Circle = Circle {
    translateX: 250, translateY:250
    radius: 10
    fill: Color.BLACK
}

var timeline: Timeline = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames : [
        KeyFrame {
            time : 30ms
            canSkip: false
            action: function() {
                                  // Player
                if (moveRight) {
                    var newX = player.translateX + PLAYER_BALL_STEP;
                    if (newX < playingField.boundsInLocal.maxX - player.radius - playingField.strokeWidth) {
                        player.translateX = newX
                    }
                }
                if (moveLeft) {
                    var newX = player.translateX - PLAYER_BALL_STEP;
                    if (newX > playingField.boundsInLocal.minX + player.radius + playingField.strokeWidth) {
                        player.translateX = newX
                    }
                }
                if (moveUp) {
                    var newY= player.translateY - PLAYER_BALL_STEP;
                    if (newY > playingField.boundsInLocal.minY + player.radius + playingField.strokeWidth) {
                        player.translateY = newY
                    }
                }
                if (moveDown) {
                    var newY= player.translateY + PLAYER_BALL_STEP;
                    if (newY < playingField.boundsInLocal.maxY - player.radius - playingField.strokeWidth) {
                        player.translateY = newY
                    }
                }
            }
        }
    ]
}

Stage {
    title: "Ballgame"
    scene: Scene {
        fill: Color.CHOCOLATE;
        width: 430, height: 400
        content: Group {
            focusTraversable: true
            translateX: 10, translateY:10
            content: [
                playingField,
                player
            ]
            onKeyPressed : function (e: KeyEvent){

              if (e.code == KeyCode.VK_LEFT) {
                    moveLeft = true;
              }
              if (e.code == KeyCode.VK_RIGHT) {
                    moveRight = true;
              }
              if (e.code == KeyCode.VK_UP) {
                    moveUp = true;
              }
              if (e.code == KeyCode.VK_DOWN) {
                    moveDown = true;
              }
            }
            onKeyReleased : function (e: KeyEvent){
              if (e.code == KeyCode.VK_LEFT) {
                    moveLeft = false;
              }
              if (e.code == KeyCode.VK_RIGHT) {
                    moveRight = false;
              }
              if (e.code == KeyCode.VK_UP) {
                    moveUp = false;
              }
              if (e.code == KeyCode.VK_DOWN) {
                    moveDown = false;
              }
            }
        }
    }
}

// Start game
timeline.playFromStart();

Starting GNOME Development – Starting your own project

Tuesday, February 17th, 2009

I had already posted a *very* quick start guide on how to start working on existing GNOME projects. Today I will focus on how to start your own GNOME/GTK+ project.

What programming language do I use?

The mother of all questions. While you may know that you want to do GNOME/GTK+ development the choice of languages with excellent bindings is sheer overwhelming. Unfortunately it seems that picking a language and sticking with it always involves a trade off. Anyway here are a few thoughts about picking the right language just in case you can’t make the choice on your own.

C is the language most of GNOME is written in. If you want to later contribute to core GNOME projects, C is worth learning and there is no better way than writing your own little project. The drawback is the amount of boilerplate code, the need for memory management and if you come from another language the need not only to familiarize yourself with GTK+, but also with a new programming language.

Python, C#, Java, Perl, C++ all of these languages have official GNOME bindings making all of these languages a good choice. If you come from one of these languages you will probably be up and running quite quickly. Python and pygtk are widely used in GTK+ development. C# runtime is developed in the mono project and is used in several more recent GNOME projects. Java has the benefit of running on top of the very fast Java Virtual Machine (JVM). The documentation of the Java GNOME bindings are not up to par with the other languages, but that is supposed to change in the near term and might be something you can help with? The Perl GTK+ project is gtk2-perl and C++’s project is gtkmm.

Other languages. Check the official GNOME bindings for any of the other languages. You will probably do just fine using any of these if you already know the language.

Then there isĀ Vala. Vala is a new high level language that compiles into native C code and thus will be as fast or at least almost as fast as apps written in C. Vala can therefore be used to write core GNOME libraries and apps because it does not depend on a runtime like Java, C# and Python for example do. The irc channel is always crowded so there seems to be quite some interesst in this language. Is it the future of GNOME development? I don’t know, but you should keep an eye on the project.

Summing up I would suggest to be very pragmatic with your choice. Stick to what you know and you will find success a lot quicker. After all the many GTK+ bindings have the intention of letting programmers program with whatever language they like most. If you learned the basics of GTK+ and have written your first little apps take a look at other languages. Each language has its own strengths and merits and soon you might choose a different language depending on the type of GTK+ project you are writing.

If you are new to programming and do not yet have a preferred programming language I would suggest getting started with either Python, Java or C# (I might give a slight edge to python).

Use Glade for GUI development?

So you have chosen a programming language. Now do I hand code my GUIs or do I use Glade as a graphical user interface builder? My advice would be to get started by hand coding a few of the basic widgets. Seeing the code and seeing how it works gives you a much better understanding of the GTK+ widgets and programming principles. Once you have a basic understanding of events, signals, arranging widgets etc. go ahead and start learning to use glade. For most straightforward GUIs this tool can save you a tremendous amount of time. The place to start learning to use glade is here.

I heard something about GtkBuilder instead of libglade?

Everything you need to know about this can be read Micah Carrick’s blog.

What tutorials are worth following?

  1. The best tutorial I have found to get you started quickly is Micah Carrick’s tutorial.
  2. Then there is the book Foundations of GTK+ development. So far I think it is a good resource and I will post a detailed review sometime in the near future. The only apparent problem is that the book focuses only on the C programming language and that will not be of great use if you do not plan to write your code in C.
  3. The official GTK+ tutorial is lengthy but a good starting point. Programming language is once again C.
  4. For python there is the pygtk tutorial.
  5. For Java there is this tutorial which gives you a quick overview of how to develop with javagnome bindings including using glade.
  6. For Vala there is the Vala tutorial.
  7. For C# and GTK# there are a whole bunch of articles and tutorials.