Java game framework

In this tutorial I will present a basic game flow and a game framework that I've made and that we will use for making java games.
It’s good to have a well organized framework so that the code is readable and that you can easier found what you are looking for.

Game framework classes

A basic game flow

The diagram below shows a basic game flow that almost all games have.

Basic game flow diagram

The game flow in my framework goes like this:
In the state “Launch Game”, first a window is created then a panel is putted on for drawing and listening to the keyboard and mouse events. In this state, then follow an initialization of variables and objects, and loading files (images, sounds...) for use when we not yet in the actual game (eg. main menu).
When the state “Launch Game” is finished we are in “Main Menu” state. Here player can choose between “Exit Game”, “Other Menus” or “New Game”. If “Exit Game” is selected, then the game ends. If “Other Menus” is selected, then some other menu is shown (options, credits or something else). When “New Game“ is selected, the actual game is created.
In state “New Game” first initialization of variables and objects happen, than loading files for the game. Then as it’s shown on the image an update of game happen and then drawing on the screen and then again update and so on.
Just like a “New Game” have its update and draw, so the “Main Menu” has its update and draw for updating and drawing the main menu.

Framework

Game framework classes

This framework consists of four classes.
First is the “Window.java”; here is created a window and its properties. Second one is the “Canvas.java”; here is created a panel on which we will draw and listen for keyboard and mouse events. The third is the "Framework.java"; this class controls the game, update and draws it on the screen. The last, fourth class is the "Game.java"; this is the actual game that is created and controlled by "Framework.java".

In the source code (that you can download at the bottom of this page) I commented the code, but here I will explain each class and how the Framework works.

Window.java

In this class window and its properties are created. This class also creates an instance of Framework.java that extends Canvas.java that extends the JPanel which is then putted on the window.

Here, in this class are three things to set up.
First you have to set the title of the window - name of the game.

	this.setTitle("Game title goes here.");
	

Second and third thing to set is the size of the window - full screen or window mode. If you want game to be in full screen then put “true” into if condition. Otherwise insert a false and set the size of the window in else at this.setSize(width, height);.

	if(false) // Full screen mode
	{
	    // Disables decorations for this frame.
	    this.setUndecorated(true);
	    // Puts the frame to full screen.
	    this.setExtendedState(this.MAXIMIZED_BOTH);
	}
	else // Window mode
	{
	    // Size of the frame.
	    this.setSize(1024, 768);
	    // Puts frame to center of the screen.
	    this.setLocationRelativeTo(null);
	    // So that frame cannot be resizable by the user.
	    this.setResizable(false);
	}
	
Canvas.java

This class extends the JPanel that we will use for drawing. We override the JPanel method paintComponent(Graphics g), so that call our method Draw(Graphics2D g2d) that we will use for drawing game to the screen.

This class implements a KeyListener and a MouseListener so that we can get an input from the players. You can see in the constructor that we add a key and a mouse listener to the JPanel.
A KeyListener and a MouseListener have some methods that we have override.

KeyListener
have a keyPressed(KeyEvent e), keyReleased(KeyEvent e) and keyTyped(KeyEvent e) methods. We are override keyPressed(KeyEvent e) and keyReleased(KeyEvent e) methods so that they save the state of the keys to our array keyboardState. When the key is pressed a “true” is saved into array on the index of the corresponding key. When key is released a “false” is saved. We can check if a key is hold down with method keyboardKeyState(int key) that return true or false for corresponding key.
Into keyReleased(KeyEvent e) method we add one more line where our method keyReleasedFramework(KeyEvent e) is called, that method we will use in Framework.java.
So we can respond to user keyboard input in two ways. We can check state of a key with keyboardKeyState(int key) method (eg. we will use this for moving a player character) or we can do some action when a keyReleased(KeyEvent e) method is invoked (when a key is released) and calls our method keyReleasedFramework(KeyEvent e).

MouseListener
have a mousePressed(MouseEvent e), mouseReleased(MouseEvent e), mouseClicked(MouseEvent e), mouseEntered(MouseEvent e) and mouseExited(MouseEvent e) methods. Same as we save key status for keyboard, we now save button states for mouse into mouseState array. Again we have method to check if mouse button is hold down. The method is mouseButtonState(int button).

In this class you can set up, if you want, that mouse cursor disappears. You can use this when you want to draw your own cursor or if the game doesn’t need one. If you don’t want mouse cursor to be visible just insert “true” into if condition.

	if(false)
	{
	    BufferedImage blankCursorImg = 
	    new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
	    Cursor blankCursor = Toolkit.getDefaultToolkit().
	    createCustomCursor(blankCursorImg, new Point(0, 0), null);
	    this.setCursor(blankCursor);
	}
	
Framework.java

We will write our code into this class and into Game.java.

Variables:
On the start of this class we have variables frameWidth and frameHeight which will be used to store a size of panel that we will use to draw the game on.
Next variable is secInNanosec that holds time of one second in nanoseconds. This can be used to get game time, which is saved in gameTime variable, into seconds.
Next variable is milisecInNanosec which we use to calculate the sleep time for the game thread from nanoseconds into milliseconds.
Then we have a GAME_FPS variable which one specifies how many times per second game should update and draw on the screen. You can change this depending on how fast you want your game to update.
Next variable GAME_UPDATE_PERIOD is used to calculate the sleep time for the game thread so the game loop can meets the GAME_FPS.
Then we have enum GameState where we have saved all possible game states and next variable gameStatus holds one of this states. Variable gameState holds the current state of the game.
Next variable is gameTime that holds elapsed game time in nanoseconds. We could use it to let player know for how long he’s playing the game or calculating the delay between creating enemies or something like this. Next one is lastTime that we use to calculate game time.
Last variable is game; it is the object of the Game.java class. We will create this object when we start the game.

Methods:
First we have class constructor Framework(). In this constructor we first have statement super(); that calls constructor of Canvas.java class with which we extended this Framework.java class. Then we set the game state to “VISUALIZING” and then start the game loop with calling a GameLoop() method in new thread.
Then we have Initialize() and LoadContent() which are intended to initialize class variables and objects and to load files for this class.
Then we have the GameLoop() method for updating game logic and to call draw method.
Follows the Draw(Graphics2D g2d) method that is called from GameLoop() method. Draw method is used for drawing game to the screen.
Next are methods which you will call when you want to start the game or restart the game; methods are newGame() and restartGame().
Next is a method mousePosition() that return position of the mouse pointer. If the statement this.getMousePosition(), in this method, return null or if its throw exception then this method return Point(0, 0) mouse position. Statement this.getMousePosition() return null when, if the frame is not in full screen, mouse is not on the frame.
Then we have keyReleasedFramework(KeyEvent e) method that is called every time that keyboard key is released.
Last method is mouseClicked(MouseEvent e); this method is called whenever the mouse button is clicked.

Flow in this class:
First in the constructor a game state is changed into “VISUALIZING”. Then the GameLoop() method is called, in new thread so that a window can be created to finish. In this method we have endless while loop which is actual game loop. In this loop a game logic is updated and then repaint() method is called that calls paintComponent(Graphics g) method from Canvas.java which calls our method Draw(Graphics2D g2d) that we have in this Framework.java class. Then this game thread is putted to sleep for some time that is necessary to meet the target updating rate that we have specify at the beginning of this class in variable GAME_FPS.
For the first time we get to the game loop, game status is in the “VISUALIZING” state. We are in this state until frame is visible so that we can get size of the panel. When we get size the game state is changed to “STARTING”. In this state we call Initialize() and LoadContent() methods and when they are finished we change game state to “MAIN_MENU”. Initialize() and LoadContent() methods are intended to set the variables and objects and to load files for this class. When we are in “MAIN_MENU” state, we can show main menu or just call newGame() method to start the actual game. Method newGame() sets game time to zero and create a game object. When new object of game is created and all its files are loaded and all variables are set the game status changes into “PLAYING”. While the game variables are setting up and game files are loading, the game state is “GAME_CONTENT_LOADING”. In this state we can draw to the screen some “game is loading” screen. Then we have two more states, one is “GAMEOVER”. In this state you will draw some game statistics (eg. score, time…) and let know player how to restart the game. When you need to restart the game just call restartGame() method. This method will reset the game time to zero, then call the game restart method game.RestartGame() and change the game state to “PLAYING”. Last state that I didn’t yet mention is “OPTIONS”. Here you can make some options menu (eg. turn of the sound).
You can always change, delete or add some other states of the game.

Game.java

This class contains the actual game.

In the constructor we change the game state to the “GAME_CONTENT_LOADING” state. Then we call Initialize() and LoadContent() methods in new thread so that we can draw “game is loading screen”. When initializing and loading is finished the game state is changed to “PLAYING” and the game begin. From now on the UpdateGame(long gameTime, Point mousePosition) and Draw(Graphics2D g2d, Point mousePosition) methods are called from Framework.java. Into UpdateGame method write code for updating the game and into Draw method write code that draws the game to the screen. In this class we have one more method, that is RestartGame() which is called when the game have to be restarted. So you have to put into this method code that will reset variables that have to be reset for new game.


Best way to understand this framework is to look at next two tutorials and see it in an action.

This framework also includes Animation.java class for animating and Sound.java class for sound. I will introduce these two classes in further tutorials.



Download game framework source code.