TheProgrammingZone's front page. All the latest programming and game development news, as well as this week's feature game project!
Visual Basic
Assembly aritcles
Source Code
Visual Basic
Game Projects
 Game projects under development by members of the TheProgrammingZone Community. Show them your support, and check out their games!
Message Board
 A forum to interact with your fellow programmers.
Visual Basic
Assembly Links
TheProgrammingZone's products. Check out some of our in house products that we made.
You want to contact the guy behind TheProgrammingZone? Here's where to do it!


Java Game Tutorial - Part 2 - by John Croucher - page 1

pages: prev | 1 | 2 | next
Welcome back.
In this tutorial I will show you how to implement buffering into your app. First here are some details on how buffering works.
The current app you have flickers. This is because you can actually see the computer drawing the images to the screen. If you use buffering the computer draws it to one area and then only once it has finished drawing the objects it displays it on the screen.
There are different ways of doing buffering, but for now I will stick with the easiest so you can get an idea of how it all works.
If you have trouble understanding that example this way may help. I like to think of buffering like someone drawing on a piece of paper. If you are watching someone draw on a piece of paper you can see every movement the person makes. But if say the person has 2 pieces of paper it could make things better. The person gives you one to look at. While you are looking at that piece of paper the person goes on and draws on the blank one. Once the person has finished drawing that one, the person will switch pages with you, and start drawing again. I know it’s a lame way of putting it but it’s simple.

Now that all the background is out of the way we will now get to modifying the code from the first tutorial.

First you will need to import:


We also have two new variables to add:

BufferedImage bufferdImg;
Graphics2D bufferdImgSurface;

Scroll down until you find the function init() and add the following code:

bufferdImg = (BufferedImage)createImage(width, height);
bufferdImgSurface = bufferdImg.createGraphics();

These two lines of code will set up the area to be drawn to.

The last step is to modify the update(Graphics g) function. The code is as follows:

public void update(Graphics g)
Graphics2D g2 = (Graphics2D)g;
// Set the background color.

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

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

g2.drawImage(bufferdImg, 0, 0, this);

As you see we have changed it from drawing to ‘g2’ to ‘bufferedImgSurface’, and only at the very end drawing the whole frame to the screen:
g2.drawImage(bufferdImg, 0, 0, this);

Now it’s ready to go. You should now have a reduction in the flickering. As I said it’s not the best way to do it but it works and it’s easy so it is fine for now.

This next section is to show you how collision detection will be working in the game. You will notice that there is already some collision detection with the circle bouncing around the screen, but we will now expand on this. Please note most of this code will not be needed in our game so you may want to make a copy of your current file. Also you can skip this section if you wish but I recommend at least reading through it.

Again we will start in the variables section. Locate the integer variable called MAX. The current value of this is 1 (one circle). We want to have 2 circles bouncing around the screen so we will change MAX to 2.

Next we need to add two new variables:
boolean collided=false;
float dist;

‘collided’ is only true if the distance between the two points is less than the specified amount.
‘dist’ is the distance between the two points.

In the ‘init()’ function add:


This code is just the same as previous code so it shouldn’t need explaining.

This next section of code should go in the ‘run()’ function just after the two circles have been moved:

dist = (int)(Math.sqrt(Math.pow((currentX[0]+20)-(currentX[1]+20),2) + Math.pow((currentY[1]+20)-(currentY[1]+20),2)));

if(dist < 20)
collided = true;
collided = false;

The first line of code is the distance formula:
sqrt(pow((X1)-(X2),2) + pow((Y1)-(Y2),2)))

This formula just calculates the distance between two points when given the X and Y cords.

The next section is just an if statement that says if the distance between the two points is less than 20 then they must be touching so set ‘collided’ to true.

Just a note. You may notice that in the distance formula I have the current position +20. This is because I am adding the diameter of the circle or you would only get the absolute X/Y cord.

The last thing to add is to the ‘update(Graphics g)’ function:
bufferdImgSurface.fillOval(currentX[1], currentY[1], 20,20);


Add those two lines just b4:
g2.drawImage(bufferdImg, 0, 0, this);

Compile and run.
You should notice that the two circles both bounce around the screen. When the two circles are touching the word “Collided” is displayed in the top left hand corner.

This is one of the simplest methods of collision detection and the method we will be using to detect a collision between the bullets, player and the enemy(s).

It’s been a long time but now all the basics are now out of the way and its now time for us to start working on the actual game.

This will require many modifications and additions to the code. Just to give you an idea of the size of the game, it’s around 7 pages.

In this game we will be using the mouse for input we must do a few things to set up the mouse for input. First you must import the following package:

You must also add to the class line:
public class Game extends Applet implements Runnable, MouseMotionListener, MouseListener

That is all to the mouse section for now. We will be dealing with the mouse listener more throughout the code, but for now we will move onto the variables.

First you can go and delete these variables as they are no longer needed:
int directionX[] = new int[MAX];
int directionY[] = new int[MAX];
There are a lot of new variables to add so I am just going to give you the whole list that we will be using to make your’s and my life easier. Some of these you will already have, some you won’t. Also the comments next to them should explain them pretty well:

BufferedImage bufferdImg;
Graphics2D bufferdImgSurface;

Thread gameThread;

int width=400, height=400, MAX=50, speed=10;

int currentX[] = new int[MAX];
int currentY[] = new int[MAX];

int step=0, // Number of movements left/right
direction=1, // Current left/right direction (0=left, 1=right)
shipX=width/2-10, // Current player X possition
shipY=height-45, // Current player Y possition
mbx=-10, // The mouse position after mouse down, sets the_
mby=-10, // enemy bullet position to this.
randomShoot=0, // Used to work out which enemy is shooting
health=50, // The players health
BNUM=10, // Number of bullets
playing=0; // Are is the game playing (0=Playing, 1=Paused, 2=Game Over, 3=Win)

int bX[] = new int[BNUM]; // Bullet X pos.
int bY[] = new int[BNUM]; // Bullet Y pos.

int ebX[] = new int[BNUM]; // Enemy Bullet X pos.
int ebY[] = new int[BNUM]; // Enemy Bullet Y pos.

long start=0, // Frame start time
tick_end_time, // End frame time
tick_duration, // Time taken to display the frame
sleep_duration; // How long to sleep for

static final int MIN_SLEEP_TIME = 10, // Min time to sleep for
MAX_FPS = 20, // Max frame rate.
MAX_MS_PER_FRAME = 1000 / MAX_FPS; // MS per frame

float fps=0, // Current frame rate
dist; // Distance between 2 points

The first function in our code is ‘start()’ this has no changes so lets move to the next one.

Next is ‘init()’. As you remember this function sets our initial values. This has a few additions as follows:

This section of code is for drawing a grid of circles 10 by 5.
Set up local integer variables for keeping track of what we have drawn.

int row=10, // Current Y position
col=10, // Current X position
count=0; // How many circles have been drawn

We will set the first circle to the initial values of ‘row’ and ‘col’ so we have a starting point to work from:

This section actually sets the coordinates for each circle:

for(int i=0; i < 50; i++) {


This works by looping through each circle position. This in effect draws 10 circles with the Y value of 10. After it has looped through 10 times count will = 10. It will then add 25 to the ‘row’ value and draw another 10 circles with the Y value of 35. Each loop the X position is also moved across 25 points. It will keep doing this until 50 circles have been given values.

The following two lines of code are used to start the mouse listener “listening” on the applet:

‘MouseMotionListener’ is used for picking up the motion of the mouse. Things such as the X,Y cords and if the mouse is on the applet or not.
“MouseListener’ is used for detecting mouse clicks.

The last section in the ‘init()’ function is just simply to give all the bullets a position off of the screen so they are hidden and ready to be fired.
for(int i=0; i < BNUM; i++){

The next function is ‘run()’. So many changes have been made to this function that you can basically delete it and I will go through it.

while(true){ // Starts the game loop
start = System.currentTimeMillis(); // Sets the current time

if(playing==0){ // Are we playing or is the game over?

Next section we will move the aliens left and right. It will first move them to the right by adding 1 to step until step is greater then 15. When this occurs it will then set step to 0 and change the direction to 0 which means move them to the left. After it moves 15 positions it will also move down one row.

for(int i=0; i < MAX; i++){
if(step > 15) {
} else {
for(int j=0; j < MAX; j++)

pages: prev | 1 | 2 | next
TheProgrammingZone 2019
Site Map