Tower Defense Demo

Simple flicker-free Java animation!
download the demo (unfinished test version)
This unnamed Tower Defense type game is my team's project for RIT's 2007 12 hour programming competition. We were trying to get a full game together inside of the tight deadline, but didn't quite get it to the point being fun. It does however make for a good interactive tech-demo of smooth java 2d animation. Here is a quick example of how I made the the double buffering work:

The gameplay area was a Canvas object, a type of renderable swing component.
public class BufferedCanvas extends Canvas implements ActionListener {

Image backbuffer_image;
Graphics backbuffer_graphics;

// something to fill the screen with
Image scenery;
Timer timer;

/**
* Sets up a double buffered canvas
*/
public void configure(int xpos, int ypos, int xsize, int ysize){
this.setBounds(xpos,ypos, xsize, ysize);

// Good place to add listeners to this canvas
//addMouseListener(this);
//addMouseMotionListener(this);

// Create a image object to draw to as the backbuffer
JFrame f = new JFrame("temp");
f.addNotify();
backbuffer_image = f.createImage(xsize, ysize);
backbuffer_graphics = backbuffer_image.getGraphics();

// load an image to use as scenery
scenery = (new ImageIcon("images//example_scenery.gif")).getImage();

// quick and drity timer to force repainting of the screen
// the recall speed should be adjusted to a realistic
// value for the needs of your program and the speed of the
// hardware it will run on
timer = new Timer(1, this);
timer.setInitialDelay(0);
timer.setCoalesce(true);
timer.start();
}

// redraw on timer AND action events
public void actionPerformed(ActionEvent e) {

// Draw the scenery image over the entire frame
// or alternativly, fill with a solid color
backbuffer_graphics.drawImage(scenery, 0, 0, null);

/*
call whatever drawing mathods you like here,
let them draw only to the backbuffer_graphics object
*/
// grid.draw(backbuffer_graphics);
// entities.draw(backbuffer_graphics);

// queue up a repaint
repaint();
}

// draw the contents of the backbuffer on the
// frontbuffer (this canvas object)
public void paint(Graphics g)
{
g.drawImage( backbuffer_image, 0, 0, this );
}

// add listeners here for mouse, keyboard, etc
// ...
}

No comments: