Reputation: 6626
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;
}
Upvotes: 1
Views: 6456
Reputation: 1
import acm.graphics.; import acm.program.;
public class BrickInTheWall extends GraphicsProgram {
private static final int BRICK_WIDTH = 20;
private static final int BRICK_HEIGHT = 10;
private static final int BRICK_IN_BASE = 10;
public void run(){
int w=BRICK_WIDTH * BRICK_IN_BASE + 200, h = BRICK_HEIGHT * BRICK_IN_BASE+200;
for(int a = 1; a <= BRICK_IN_BASE; a++) { for(int i = 0; i < a; i++) { GRect rect = new GRect((w*2) - BRICK_WIDTH/2*a+BRICK_WIDTH * i, 40 + BRICK_HEIGHT * a,BRICK_WIDTH, BRICK_HEIGHT); add(rect);
}
}
}
}
Upvotes: 0
Reputation: 88727
my problem is the pyramid should be centered in the window
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_WIDTH
x = (area.width-pyramid_width)/2
BRICK_IN_BASE * BRICK_HEIGHT
y = (area.height-pyramid_height)/2
Besides that, note that for each level above the base you would have to add BRICK_WIDTH/2
to 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 * j
BRICK_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).Upvotes: 2
Reputation: 8255
So you need to find the offsets for x and y. The width of the pyramid is BRICK_WIDTH * BRICK_IN_BASE, so you take half the width of the window and subract (BRICK_WIDTH * BRICK_IN_BASE) / 2. You use the same logic to find the y offset.
int x = xOffset + BRICK_WIDTH * j ;
int y = yOffset + BRICK_HEIGHT * i;
I'm not familiar with the acm package, depending on how it implements GRect this may still be half a brick off. But you can solve that easily.
Upvotes: 1