I'm creating ATARI BREAKOUT, using the acm.graphics
library and I'm trying to access a "brick" outside of my for loop to delete it. I can't figure out any other way to create the bricks without the for loop. Help?
GRect brick = new GRect(brickwidth, brickheight);
for(j = 1; j <= nrows; j++) {
for(i = 0; i < bricksperrow; i++) {
brick.setLocation(i*(brickwidth + brickSep) + 1, brickoffset + j*(brickheight + brickSep));
if(j == 1 || j == 2) {
brick.setColor(Color.RED);
brick.setFilled(true);
}
else if(j == 3 || j == 4) {
brick.setColor(Color.ORANGE);
brick.setFilled(true);
}
else if(j == 5 || j == 6) {
brick.setColor(Color.YELLOW);
brick.setFilled(true);
}
else if(j == 7 || j == 8) {
brick.setColor(Color.GREEN);
brick.setFilled(true);
}
else if(j == 9 || j == 10) {
brick.setColor(Color.CYAN);
brick.setFilled(true);
}
add(brick);
}
}
I guess you want to create many bricks in for loop.
You are doing it wrong, per iteration you are just changing a position of one brick. You need to create a new brick per iteration and save its reference into some structure preferably a matrix of [nrows, bricksperrow] dimensions.
Here's how:
GRect[][] bricks = new GRect[nrows][bricksperrow];
for(j = 1; j <= nrows; j++) {
for(i = 0; i < bricksperrow; i++) {
bricks[j - 1][i].setLocation(
i*(brickwidth + brickSep) + 1,
brickoffset + j*(brickheight + brickSep));
if(j == 1 || j == 2) {
brick.setColor(Color.RED);
brick.setFilled(true);
}
else if(j == 3 || j == 4) {
brick.setColor(Color.ORANGE);
brick.setFilled(true);
}
else if(j == 5 || j == 6) {
brick.setColor(Color.YELLOW);
brick.setFilled(true);
}
else if(j == 7 || j == 8) {
brick.setColor(Color.GREEN);
brick.setFilled(true);
}
else if(j == 9 || j == 10) {
brick.setColor(Color.CYAN);
brick.setFilled(true);
}
add(bricks[j - 1][i]);
}
}
This way you can have global matrix of bricks from where you can delete any entry.