Original Post
I am a C++ programmer who recently started to learn java because I want to write applet games. I am using java 1.1 so people wont have to download java 2 to run it. The problem I am having is that I just can’t get the speed I need.
I know good games can be written in java 1.1 because I see them on the Internet.
Below is a simple applet that bounces 10 rects around with double buffering.
I think it is the double buffering that is killing it.
Even running that in 500 x 300 it just goes slow on my computer(I planned to do the game at 800 x 600)
Could people look over the code and see if I am doing something wrong?
Or maybe I should just give up java and make the game in c++.
Thanks for any help
import java.awt.*;
import java.applet.*;
import java.awt.image.*;
public class BounceRects extends Applet implements Runnable {
Thread MainThread;
Graphics BackBuffer;
Image BackBufferImg;
final int SCR_X = 500;
final int SCR_Y = 300;
final int PAUSE_PER_FRAME = 50;
final int RECT_NUM = 10;
private boolean drawRects = false;
CRect rects[];
public void init() {
rects = new CRect[RECT_NUM];
for (int i = 0; i < RECT_NUM; i++) {
rects[i] = new CRect();
}
BackBufferImg = createImage(SCR_X, SCR_Y);
BackBuffer = BackBufferImg.getGraphics();
}
public void start() {
if(MainThread==null) {
MainThread = new Thread(this);
MainThread.start();
}
}
public void stop() {
MainThread=null;
}
public void run() {
drawRects = true;
Thread currentThread = Thread.currentThread();
while(MainThread == currentThread) {
repaint();
for (int i = 0; i < RECT_NUM; i++ ) {
rects[i].update();
}
try {
MainThread.sleep(PAUSE_PER_FRAME);
}
catch(InterruptedException e) {}
}
}
public void update(Graphics g) {
paint(BackBuffer);
g.drawImage(BackBufferImg, 0, 0, this);
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, SCR_X, SCR_Y);
if (drawRects) {
for (int i = 0; i < RECT_NUM; i++) {
rects[i].draw(g);
}
}
}
class CRect {
public int x, y, w, h, vx, vy;
CRect() {
w = (int) (Math.random() * 40) + 5;
h = (int) (Math.random() * 40) + 4;
x = (int) Math.random() * (SCR_X - w);
y = (int) Math.random() * (SCR_Y - h);
vx = (int) (Math.random() * 10) - 5;
vy = (int) (Math.random() * 10) - 5;
}
public void update() {
x += vx;
y += vy;
if ((x < 0) || ((x + w) > SCR_X)) {
vx = -vx;
}
if ((y < 0) || ((y + h) > SCR_Y)) {
vy = -vy;
}
}
public void draw(Graphics g) {
g.setColor(Color.red);
g.drawRect(x, y, w, h);
}
} // end class CRect
} // end class BounceRects