cs106a – Assignment #3 – Task #1

The complete specification of assignment #3 can be found as part of the stream at iTunes.

Set up the bricks

Before you start playing the game, you have to set up the various pieces. Thus, it probably makes sense to implement the run method as two method calls: one that sets up the game and one that plays it. An important part of the setup consists of creating the rows of bricks at the top of the game, which look like this:

cs106a – assignment #3 – task #1

The number, dimensions, and spacing of the bricks are specified using named constants in the starter file, as is the distance from the top of the window to the first line of bricks. The only value you need to compute is the x coordinate of the first column, which should be chosen so that the bricks are centered in the window, with the leftover space divided equally on the left and right sides. The color of the bricks remain constant for two rows and run in the following rainbow-like sequence: RED, ORANGE, YELLOW, GREEN, CYAN.


First define the position of the top left brick and setup an array of the wanted colors. Iterate over the rows and over the bricks in a single row. For every first brick in a row reset the x position and set the new color. At the end of a row adjust the y position:

	private void setupBricks() {
		int y = BRICK_Y_OFFSET;
		int firstX = (WIDTH - BRICK_WIDTH * NBRICKS_PER_ROW - BRICK_SEP * (NBRICKS_PER_ROW - 1)) / 2;
		Color[] colors = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.CYAN};
		
		for (int j = 0; j < NBRICK_ROWS; j ++) {
			int x = firstX;
			Color c = colors[j / 2];
			for (int i = 0; i < NBRICKS_PER_ROW; i++) {
				GRect brick = new GRect(BRICK_WIDTH, BRICK_HEIGHT);
				brick.setLocation(x, y);
				brick.setFilled(true);
				brick.setColor(c);
				add(brick);
				x += BRICK_WIDTH + BRICK_SEP;
			}
			y += BRICK_HEIGHT + BRICK_SEP;
		}
	}

The code for this assignment is available on github.

FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published.