Write a GraphicsProgram subclass that draws a pyramid consisting of bricks arranged in horizontal rows, so that the number of bricks in each row decreases by one as you move up the pyramid, as shown in the following sample run:
The pyramid should be centered at the bottom of the window and should use constants for the following parameters:BRICK_WIDTH The width of each brick (30 pixels) BRICK_HEIGHT The height of each brick (12 pixels) BRICKS_IN_BASE The number of bricks in the base (14)The numbers in parentheses show the values for this diagram, but you must be able to change those values in your program.
Start by drawing a single brick, which is basically a black rectangle with the given width and height at a certain start point:
private void drawBrick(double x, double y) { GRect rect = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT); rect.setColor(Color.BLACK); add(rect); }
A row of bricks consists of a given number of bricks with a constant y value. The x value of the brick depends on the current position of the brick:
private void drawRow(double x, double y, int bricks) { for (int i = 0; i < bricks; i++) { drawBrick(x + i * BRICK_WIDTH, y); } }
Finally, to draw the pyramid, calculate the position of the first brick of the first row, and then iterate over all rows:
public void run() { double x = (getWidth() - BRICKS_IN_BASE * BRICK_WIDTH) / 2; double y = getHeight() - BRICK_HEIGHT; for (int row = 0; row < BRICKS_IN_BASE; row++) { drawRow(x, y, BRICKS_IN_BASE - row); y -= BRICK_HEIGHT; x += BRICK_WIDTH / 2; } }
The code for this assignment is available on github.