Skip to content

Instantly share code, notes, and snippets.

@dsch31
Forked from hutchdoescoding/Pyramid.java
Created August 3, 2018 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsch31/6754f27a057fa2357494e2de66511a9a to your computer and use it in GitHub Desktop.
Save dsch31/6754f27a057fa2357494e2de66511a9a to your computer and use it in GitHub Desktop.
This is my solution to the 'Pyramid' assignment for the Stanford CS106A lectures.
/* File name: Pyramid.java
* This program will display a pyramid centered within the screen.
*/
import acm.program.*;
import acm.graphics.GRect;
public class Pyramid extends GraphicsProgram {
public void run() {
// I realize I didn't have to use a separate method, and could have placed all the code
// in the run() method, but I figured this would be better in case I wanted to expand the program later on
DrawPyramid();
}
// Declared the constants for the Width, Height, and amount of starting bricks.
public static final int BRICK_WIDTH = 20;
public static final int BRICK_HEIGHT = 10;
public static final int BRICKS_IN_BASE = 8;
/* Create the method for drawing the Pyramid
* This first part of this method Gathers the Canvas Height and Width and then stores them in variables.
* It then calculates the center line of the canvas, and creates variables for where the first brick should be placed.
* I realize that the 'StartingPointY' variable is a little redundant, but it was for my benefit when implementing
* further down.
*/
private void DrawPyramid() {
int CanvasWidth = getWidth();
int CanvasHeight = getHeight();
int CanvasMiddle = CanvasWidth / 2;
int StartingPointX = CanvasMiddle - (BRICK_WIDTH * (BRICKS_IN_BASE / 2));
int StartingPointY = CanvasHeight;
//Created an outer for loop for drawing as many rows as are in the BRICKS_IN_BASE
for (int i = 1; i <= BRICKS_IN_BASE; i++) {
int Y = StartingPointY - (i * BRICK_HEIGHT);
//The inner for loop will keep drawing bricks for as many bricks as are supposed to be in that row
for (int j = BRICKS_IN_BASE; j >= i; j--) {
int X = StartingPointX - (BRICK_WIDTH / 2) + (j * BRICK_WIDTH) - (i * (BRICK_WIDTH / 2));
add (new GRect(X, Y, BRICK_WIDTH, BRICK_HEIGHT));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment