Thursday, March 4, 2010

space invaders game

In this and following tutorials you will learn about Applets, Threads, Graphics and a few other things. By the end of this tutorial you should have the skills to make basic games in Java. For this tutorial you will be making a simple ‘space invaders’ type game.

I assume that you have basic knowledge of Java as I wont be going into the basic details of how some things work.

First we will be starting by creating an applet and drawing a circle to the applet area.

1. Create a file called ‘Game.java’.
2. Open the file.

The next step is to import the necessary packages. For now we will only be requiring 2 packages:
import java.applet.*;
import java.awt.*;

Now that the importing has been taken care of we will need to set up the Java applet by the following:

public class Game extends Applet implements Runnable
{
}

This basically gives access to the Applet class and the ‘Runnable’ makes it so we can implement threads.

The variables come next as we wish to make these ones global:

Thread gameThread;
int width=400, height=400, MAX=1;
int currentX[] = new int[MAX];
int currentY[] = new int[MAX];

I have decided to use arrays for the X and Y cords now because they will be used at a later stage. It makes it easier to set it up now rather than changing it later.
Next comes the methods. I have included methods that are currently not used at this stage but they are used later.

Start() is used for starting a new thread for the class.

public void start()
{
Thread gameThread = new Thread(this);
gameThread.start();
}


init() is used for setting the initial values

public void init()
{
currentX[0]=0;
currentY[0]=0;
}

run() is the main method we will use later. It is initialised after a new thread is started.

public void run()
{
}


paint() calls update().

public void paint(Graphics g)
{
update(g);
}

update () is where all the actual drawing is done.

public void update(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;

// Set the background color.
g2.setBackground(Color.black);

// Clear the applet.
g2.clearRect(0, 0, width, height);

// Set the drawing color to green.
g2.setColor(Color.green);

//(X pos, Y pos, Width, Height)
g2.fillOval(currentX[0], currentY[0], 20,20);
}


* Note this is an applet which means you must run it from a HTML file. The HTML code to run this applet is as follows and I will use the same code throughout this series of tutorials.