All Posts Develop Your Own Game

Published on July 9th, 2012 | by Ivan Donat

4

Develop you own games with Java

By following this tutorial you can make your own game in Java.

So first lets start with advantages of Java game programming:

- Easy and simple (relatively)

- You can make games quickly unlike C++

- A lot of libraries to help you (Example LWJGL for OpenGL)

But the disadvatages:

- Too high-level

- Memory leaks

- Slow because it’s a translator language.

Making the basic window

Java has two ways of making the game container. Applets and an actual Window.  Applets are used to start your game in web browsers and windows are like in any other game. We will work with  javax.swing  windows (You can later on switch to an external library such as Slick).

Make your main class and it should look like this:

package wildkoalas;

import javax.swing.*;

public class Game {

public static void main(String[] args){

new Game();

}

public Game(){}

}

So now you got your basic setup. Let’s make the JFrame (Window).

Add this in public space:

   JFrame frame;

And this in your constructor:

frame = new JFrame("Running"); //Running is title

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //So we can close it

frame.setSize(800,600); //This sets the size

frame.setResizable(false); //We cannot resize the window

frame.setVisible(true); //Finally show the window

You should now have something that looks like this:

So now the Game class is the window, let’s make a class Board that will draw and control everything (the core of the game). Here is some basic setup for that class:

package wildkoalas;

import javax.swing.*;

public class Board extends JPanel{ //Extends JPanel because of swing, so we can draw with it

private static final long serialVersionUID = 1L; //Just some swing stuff

public Board(){ //Constructor

setFocusable(true); //So you can add it to the frame

}

}

Now once we have board, return back to Game  and write these 2 lines of code in constructor to add the Board to the game:

Board b = new Board();

frame.add(b);

We won’t need to use Game class anymore, it’s all in Board now.

Let’s setup the timer (timer is for update method). Add this in constructor:

Timer t = new Timer(5,this);

t.start();

Now you have an error because the Board must implement ActionListener, so implement ActionListener. Then you will have to import java.awt.event.ActionListener and java.awt.event.ActionEvent.

And finally make the method actionPerformed(ActionEvent e){}

Board should look like this now:



package wildkoalas;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.*;

public class Board extends JPanel implements ActionListener{ //Extends JPanel because of swing, so we can draw with it

private static final long serialVersionUID = 1L; //Just some swing stuff

public Board(){ //Constructor

setFocusable(true); //So you can add it to the frame

Timer t = new Timer(5,this);

t.start();

}

public void actionPerformed(ActionEvent e){}

}

Now we need to make a really important part of the game. We need to calculate the time that has passed between 2 updates. So we can multiply all movement with that number tpf (time per frame) and the game will work at same speed with small and high FPS.

Add this in update (actionPerformed) method:

long beforeTime;

public void actionPerformed(ActionEvent e) {

floattpf;

tpf = System.currentTimeMillis()-beforeTime;

beforeTime = System.currentTimeMillis();

//tpf is time passed after last update

}

Also in the end of update add repaint(). It is a JPanel method which calls paint(Graphics g) so also add that method to the Board and import java.awt.* for the Graphics object.

public void paint(Graphics g){

super.paint(g); //Clears screen

}

This method is called at end actionPerformed with the repaint() command.

Try adding  g.drawString(“Hello there”, 20,20);  in paint(Graphics g) method after the super.paint(g)   and then run your game and see what it looks like.

It should look like this:

Congratulations, now you have the basic idea how to make a window and draw on it!

Key Input

Key Input is really important for games, how would games work without that?

So in Board constructor put  addKeyListener(new KeyListener(this));.

Also put these 2 new methods:

-         public void keyPressed(KeyEvent e)

-         public void keyReleased(KeyEvent e)

And import java.awt.event.KeyEvent.

Now we make the KeyListener class. Just create it and put this code in it:

package wildkoalas;

import java.awt.event.*;

public class KeyListener extends KeyAdapter{

Board b;

public KeyListener(Board b){

this.b = b;

}

public void keyReleased(KeyEvent e){ //Calls 'keyReleased'

b.keyReleased(e);

}

public void keyPressed(KeyEvent e){ //Calls 'keyPressed'

b.keyPressed(e);

}

}

Make these booleans in public space in Board:

boolean up = false, down = false, left = false, right = false;

Now add this in both new methods you  created:

int key = e.getKeyCode();

Then add this in keyPressed:

if(key == KeyEvent.VK_UP){

up = true;

}

if(key == KeyEvent.VK_DOWN){

down = true;

}

if(key == KeyEvent.VK_LEFT){

left = true;

}

if(key == KeyEvent.VK_RIGHT){

right = true;

}

And same in keyReleased but with false.

Now add these floats in local space:

float x = 50, y = 50;

And in actionPerformed add this:

float factor = 5;

if(up){

y-=factor*tpf;

}

if(down){

y+=factor*tpf;

}

if(left){

x-=factor*tpf;

}

if(right){

x+=factor*tpf;

}

factor  is speed at which player will run (we can modify it later).  Now we are almost done, just we need to draw the player. So go to your paint method and use g.setColor(COLOR) and g.fillRect(x,y,width,height).

g.setColor(Color.BLUE);

g.fillRect((int)x, (int)y, 30, 30);

And you are done! Run the game and try pressing arrow keys, now the problem is that that square we have is too fast. To fix that just change the factor in actionPerformed to a smaller number.

How the game should look:

CONGRATULATIONS ! You have just made your first game (Probably)

Thanks for following the tutorial and please comment if would you like  a more advanced one.

You can download the full source here:  http://bit.ly/Mg44Vq

PS: If you are good in Java and want to help with my 3D Science Fiction game contact me at ivandonat@gmail.com

Tags: , , ,


About the Author

Ivan Donat is a science Fiction fan (only >=speculative), don't like when people call something that has no science SF. Likes Physics a LOT. Learning Quantum Mechanics and expert programmer and game developer. You can follow me on twitter : @IvanDonat



4 Responses to Develop you own games with Java

  1. Mark Anderson says:

    Great post. Made my first game today :D Looking forward for advance tutorials.

  2. Shashwat Pradhan says:

    Looking forward for the advance one :)

  3. Jeremy Matthew says:

    Great thanks a lot for this tutorial. Looking forward to more such articles.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Back to Top ↑