User Tools

Site Tools


it-artikel:java:my-solution-on-assignment-2-problem-1

My Solution on Assignment 2 - Problem 1

This is my Solution of Assignment 2 - Problem 1 from the Computer Science Course CS106A of Prof. Mehran Sahami at the STANFORD University.

Pyramid.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;
 
/** Height 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;
 
 
	public void run() {
		CalculateCanvasDataAndSetVars();
		for( int ROW = 0; ROW <= BRICKS_IN_BASE; ROW++ ) { // for each ROW...
			// Calculate the Number of Bricks on this ROW and ...
			int BricksOnThisRow=BRICKS_IN_BASE-ROW;
			for(int BRICK=0; BRICK<=BricksOnThisRow ; BRICK++) { // for each BRICK on that ROW...
				//Calculate Bricks Starting Coordinate X,Y
				int X=MiddleX-((BricksOnThisRow*BRICK_WIDTH)/2)+BRICK*BRICK_WIDTH;
				int Y=CanvasY-ROW*BRICK_HEIGHT;
				drawBrickAt(X,Y);
			}
		}
	}
 
 
	public void CalculateCanvasDataAndSetVars() {
		/*
		 * Gets Canvas Sizes (Height and Width) and stores Data in public Class Variables
		 * so any following Method can access Data. Also Calculates and Stores the Middle of the 
		 * X-Axis for convenience and readability. 
		 */
		CanvasY = getHeight();
		CanvasX = getWidth();
		MiddleX = CanvasX/2; // determine Canvas middle of X-Axis, just for better readability.
		println("Canvas is " + CanvasX + " x " + CanvasY + " pixels.");
		println("Canvas X/2 is:" + MiddleX);
	}
 
 
	public void drawBrickAt(int X, int Y) {
		/*
		 * Draws (and also adds) a Brick at X,Y using the given Constants
		 * to the Canvas.
		 */
		add( new GRect(X,Y,BRICK_WIDTH,BRICK_HEIGHT) );
	}	
 
	// Some Class Variables i want access to from any Method. 
	public int CanvasX,CanvasY,MiddleX; 
 
}

Axel Werner 2011-02-06 15:06

it-artikel/java/my-solution-on-assignment-2-problem-1.txt · Last modified: 2022-08-31 12:30 by 127.0.0.1