I’m trying to learn Java from this book The Art and Science of Java
exercise in book The Art and Science of Java page 129

my problem is the pyramid should be centered in the window
import acm.program.*;
import acm.graphics.*;
public class pyramid extends GraphicsProgram {
public void run() {
for (int i = 0; i < BRICK_IN_BASE; i++) {
for (int j = 0; j < i; j++) {
int x = BRICK_WIDTH * j ;
int y = BRICK_HEIGHT * i;
GRect brick = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT);
add(brick);
}
}
}
private static final int BRICK_WIDTH =30 ;
private static final int BRICK_HEIGHT =20 ;
private static final int BRICK_IN_BASE = 12;
}
If you mean that you have a fixed area to draw in and the pyramid should be centered in that area:
BRICK_IN_BASE * BRICK_WIDTHx = (area.width-pyramid_width)/2BRICK_IN_BASE * BRICK_HEIGHTy = (area.height-pyramid_height)/2Besides that, note that for each level above the base you would have to add
BRICK_WIDTH/2to the x offset.Edit (clarification):
The above points apply to getting the x and y coordinates to start drawing at. Note that
x_offset + BRICK_WIDTH * jBRICK_WIDTH/2, i.e.int x = x_offset + (BRICK_IN_BASE - i - 1) * BRICK_WIDTH/2 + BRICK_WIDTH * j;(you’re starting at the top, so the level would have to be calculated as (BRICK_IN_BASE – i – 1) in order to get 11 for the top row and 0 for the bottom row).