# Drawing blocks for a 2D game background

Posted on

Problem

This draws blocks on the screen from a grid to make a background for my game. I am wondering if anyone has any suggestions on optimizing it for speed.

``````int blockwidth=blocksize-2;
//Draw coloured blocks
for (int x=0;x<sizex;x++){
int screenx=-(int)camerax+(x*blocksize);
if (screenx>-blocksize && screenx<gamewidth){
for (int y=0;y<sizey;y++){
int screeny=-(int)cameray+(y*blocksize);
if (screeny>-blocksize && screeny<gameheight){
if (tiles[x][y][0]>0){
g.setColor(new Color( tiles[x][y][1]));
//g.fillRect(screenx,screeny,blockwidth,blockwidth);
} else {
//g.setColor(new Color( tiles[x][y][1]  | 0xFFFF0000));
g.setColor(new Color( tiles[x][y][1]));
g.fillRect(screenx,screeny,blockwidth,blockwidth);

}
}
}
}
}
``````

Solution

There are a few optimizations I can see in your code.

1. creating a new Color every time is a little severe. You can do a few things here, for example, if your color palette is limited, then cache the individual Color instances. I know it sounds petty right now, but, when you add it up there are a lot of new Color instances created.

What you should at minimum do, is track your last Color used, and only create a new one if it is different.

2. Pull the `Iloader.Imagelist.get(0)` outside the loop, and have `Image image = Iloader.Imagelist.get(0)`

3. Pull calculations outside the loops where you can… and continue/break when you can too.

``````Image image = Iloader.Imagelist.get(0);
int screenx=-(int)camerax - blocksize;
for (int x = 0; x < sizex; x++){
screenx += blocksize;
if (screenx <= -blocksize) {
continue;
}
if (screenx >= gamewidth) {
break;
}
int screeny= -(int)cameray - blocksize;
for (int y = 0; y < sizey; y++){
screeny += blocksize;
if (screeny <= -blocksize)
continue;
}
if (screeny >= gameheight) {
break;
}
if (tiles[x][y][0] > 0) {
// need to set the color here? g.setColor(new Color( tiles[x][y][1]));
g.drawImage(image, screenx, screeny, screenx + blockwidth,
screeny + blockwidth, graphicsize, 0, graphicsize * 2,
graphicsize, null);
} else {
//g.setColor(new Color( tiles[x][y][1]  | 0xFFFF0000));
g.setColor(new Color( tiles[x][y][1]));
g.fillRect(screenx,screeny,blockwidth,blockwidth);

}
}
}
``````

The above code does not have the mechanism for caching the color. You should figure one out.