[code lang=”java”]
/*
* File: Pyramid.java
* Name:
* Section Leader:
* ——————
* This file is the starter file for the Pyramid problem.
* It includes definitions of the constants that match the
* sample run in the assignment, but you should make sure
* that changing these values causes the generated display
* to change accordingly.
*/
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
public class Pyramid extends GraphicsProgram {
/** Width of each brick in pixels */
private static final int BRICK_WIDTH = 30;
/** Width of each brick in pixels */
private static final int BRICK_HEIGHT = 12;
/** Number of bricks in the base of the pyramid */
//private static final int BRICKS_IN_BASE = 14;
private static final int BRICKS_IN_BASE = 20;
public void run() {
// get the middle of the window
double middle = getWidth() /2 ;
// the starting base_width
double base_width = BRICKS_IN_BASE * BRICK_WIDTH;
// where we put the first block of the row
double start_base = middle – (base_width/2);
//getting to the bottom layer
double bottom = getHeight();
// cannot change the constant, so we’ll assign another variable for
// the columns, add 1 to get to the top
int blk_up = BRICKS_IN_BASE+1;
// the non static brick_base variable
int blck_side = BRICKS_IN_BASE;
// the first loop is for the column
for(int i=1;i<blk_up;i++){
// second loop is for the row
for(int j=0;j<blck_side;j++){
// y coordinate position for the bricks
double y = bottom -(i * BRICK_HEIGHT);
// x coordinate for the bricks
double x = start_base + (j * BRICK_WIDTH);
//draws the bricks
GRect myrect = new GRect(x,y,BRICK_WIDTH,BRICK_HEIGHT);
add(myrect);
}
// subtract 1 brick from the row
blck_side -=1;
// get a new base width
base_width = blck_side *BRICK_WIDTH;
//get the new position for the start of the new row
start_base = middle – (base_width/2);
}
// subtract 1 from the column
// I don’t think this is necessary
//blk_up-=1;
}
}
[/code]