Results 1 to 14 of 14
Like Tree3Likes
  • 2 Post By Koala
  • 1 Post By Fubarable

Thread: Breakout Assignment from CS106a

  1. #1
    tech8462 is offline Member
    Join Date
    Oct 2011
    Posts
    6
    Rep Power
    0

    Default Breakout Assignment from CS106a

    Hello,

    Below is my code for the breakout assignment from CS106a, I think I have everything working correctly except for the last method in my code to update the score. I can't seem to get the score to update. Any help would be greatly appreciated. Also, please feel free to offer any constructive criticism on how I could have written my code more elegantly. Thanks in advance.

    -tech

    Java Code:
    /*
     * File: Breakout.java
     * -------------------
     * Name:
     * Section Leader:
     * 
     * This file will eventually implement the game of Breakout.
     */
    
    import acm.graphics.*;
    import acm.program.*;
    import acm.util.*;
    
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Breakout extends GraphicsProgram {
    
    /** Width and height of application window in pixels */
    	public static final int APPLICATION_WIDTH = 400;
    	public static final int APPLICATION_HEIGHT = 600;
    
    /** Dimensions of game board (usually the same) */
    	private static final int WIDTH = APPLICATION_WIDTH;
    	private static final int HEIGHT = APPLICATION_HEIGHT;
    
    /** Dimensions of the paddle */
    	private static final int PADDLE_WIDTH = 60;
    	private static final int PADDLE_HEIGHT = 10;
    
    /** Offset of the paddle up from the bottom */
    	private static final int PADDLE_Y_OFFSET = 30;
    
    /** Number of bricks per row */
    	private static final int NBRICKS_PER_ROW = 10;
    
    /** Number of rows of bricks */
    	private static final int NBRICK_ROWS = 10;
    
    /** Separation between bricks */
    	private static final int BRICK_SEP = 4;
    
    /** Width of a brick */
    	private static final int BRICK_WIDTH =
    	  (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;
    
    /** Height of a brick */
    	private static final int BRICK_HEIGHT = 8;
    
    /** Radius of the ball in pixels */
    	private static final int BALL_RADIUS = 10;
    
    /** Offset of the top brick row from the top */
    	private static final int BRICK_Y_OFFSET = 70;
    
    /** Number of turns */
    	private static final int NTURNS = 3;
    	
    /** Delay time in milliseconds */	
    	private static final int DELAY = 20;
    
    /* Method: run() */
    /** Runs the Breakout program. */
    	public void run() {
    		welcome = new GLabel("Welcome to Breakout, Bitches");
    		click = new GLabel("Get Ready!");
    		gameSetup();
    		welcomeThePlayer();
    		//playGame();
    	}
    	//Set up the game by building the bricks and creating the paddle
    	private void gameSetup() {
    		createBricks();
    		createPaddle();
    		pointCounter();
    		turnsRemaining = NTURNS;
    		numBricks = NBRICKS_PER_ROW * NBRICK_ROWS;
    	}
    	//let the games begin!
    	private void playGame() {
    		if (turnsRemaining > 0 && numBricks > 0){
    			createBall();
    			bounceBall();
    		} else if (turnsRemaining == 0); {
    			welcome = new GLabel("You have failed - again");
    			removeAll();
    			gameSetup();
    			welcomeThePlayer();
    		} 
    	}
    	//Build and color in each row of bricks
    	private void createBricks() {
    		int startY = BRICK_Y_OFFSET;
    		Color brickColor = Color.WHITE;
    		int colorInc = 0;
    		for (int i = 0; NBRICK_ROWS > i; i++) {		
    			if (colorInc == 0 || colorInc == 1) {
    				brickColor = Color.RED;
    			} else if (colorInc == 2 || colorInc == 3) {
    				brickColor = Color.ORANGE;
    			} else if (colorInc == 4 || colorInc == 5) {
    				brickColor = Color.YELLOW;
    			} else if (colorInc == 6 || colorInc == 7) {
    				brickColor = Color.GREEN;
    			} else if (colorInc == 8 || colorInc == 9) {
    				brickColor = Color.CYAN;
    			} else {
    				brickColor = Color.BLACK;
    			}
    			startY += (BRICK_SEP + BRICK_HEIGHT);
    			buildRow(startY, brickColor);
    			colorInc++;
    		}
    	}
    	
    	private void buildRow(int startY, Color brickColor) {
    		int wide = BRICK_WIDTH;
    		int high = BRICK_HEIGHT;
    		int totalWidth = (BRICK_WIDTH * 10) + (BRICK_SEP * 9);
    		int startX = (APPLICATION_WIDTH - totalWidth) / 2;	
    		for (int j = 0; j < NBRICKS_PER_ROW; j++) {
    			GRect thisBrick = new GRect(startX, startY, wide, high);
    			thisBrick.setFilled(true);
    			thisBrick.setFillColor(brickColor);
    			add(thisBrick);
    			startX += (BRICK_SEP + BRICK_WIDTH);
    		}
    	}
    	
    	private void createPaddle() {
    		int paddleWide = PADDLE_WIDTH;
    		int paddleHigh = PADDLE_HEIGHT;
    		double startPosX = (APPLICATION_WIDTH - PADDLE_WIDTH) / 2;
    		double startPosY = getHeight() - PADDLE_Y_OFFSET;
    		lastY = startPosY;
    		lastX = getX();
    		rightPaddleBound = (APPLICATION_WIDTH - PADDLE_WIDTH);
    		paddle = new GRect(startPosX, startPosY, paddleWide, paddleHigh);
    		paddle.setFilled(true);
    		paddle.setFillColor(Color.BLACK);
    		add(paddle);
    		addMouseListeners();
    	}
    	
    
    	/** Called on mouse drag to reposition the object */
    	public void mouseMoved(MouseEvent e) {
    		checkPaddleLoc(e);
    	}	
    	
    	public void mouseExited(MouseEvent e) {
    		checkPaddleLoc(e);
    	}
    	
    	public void mouseEntered(MouseEvent e) {
    		checkPaddleLoc(e);
    	}
    	
    	public void checkPaddleLoc(MouseEvent e) {
    		double mousePos = e.getX();
    		if (mousePos < 2) {
    			paddle.setLocation(1, lastY); 
    		} else if (mousePos > rightPaddleBound) {
    			paddle.setLocation(rightPaddleBound, lastY);
    		} else {
    			paddle.move(e.getX() - lastX, 0);
    			lastX = e.getX();
    		}
    		if (paddle.getX() < 0) {
    			paddle.setLocation(1, lastY);
    		} else if (paddle.getX() > rightPaddleBound) {
    			paddle.setLocation(rightPaddleBound, lastY);
    		}
    	}	
    
    	
    	private void createBall() {
    		double ballStartX = (APPLICATION_WIDTH - BALL_RADIUS) / 2;
    		double ballStartY = (APPLICATION_HEIGHT + BALL_RADIUS) / 2; 
    		ball = new GOval(ballStartX, ballStartY, BALL_RADIUS, BALL_RADIUS);
    		ball.setFilled(true);
    		ball.setFillColor(Color.BLACK);
    		add(ball);
    	}
    	
    	private void bounceBall() {
    		int numPaddleHits = 0;
    		vy = 3.0;
    		vx = rgen.nextDouble(1.0, 3.0);
    		if (rgen.nextBoolean(0.5)) vx = -vx;
    		AudioClip bounceClip = MediaTools.loadAudioClip("bounce.au");
    		while (ball.getY() < getHeight() && ball.getX() < getWidth()) {
    			pause(DELAY);
    			moveBall();
    			checkForCollision();
    			GObject collider = getCollider();
    			if (collider != null) {
    				if (collider == paddle) {
    					double paddleX = paddle.getX();
    					double ballX = ball.getX();
    					if (paddleX - ballX == 1 || (paddleX + PADDLE_WIDTH) - ballX == 1) vx = -vx;
    					vy = -vy;
    					ball.move(vx, vy);
    					bounceClip.play();
    					numPaddleHits++;
    					if (numPaddleHits == 7) {
    						vy = 2 * vy;
    					}
    				} else if (collider == score) {
    					
    				} else {
    					vy = -vy;
    					ball.move(vx, vy);
    					remove(collider);
    					bounceClip.play();
    					numBricks--;
    					Color objectColor = collider.getColor();
    					changeScore(objectColor);
    				} 
    				if (numBricks == 0) {
    					welcome = new GLabel("You have won - NERD!");
    					removeAll();
    					gameSetup();
    					welcomeThePlayer();
    				}
    			}
    		}
    	}
    	
    	private void moveBall() {
    		ball.move(vx, vy);
    	}
    	
    	private void checkForCollision() {
    		if (ball.getY() > getHeight() - BALL_RADIUS ) {
    			turnsRemaining--;
    			remove(ball);
    			pause(2000);
    			playGame();
    		} else if (ball.getY() < 0) {			
    			vy = -vy;
    			ball.move(vx, vy);		
    		} else if (ball.getX() > getWidth() - BALL_RADIUS || ball.getX() < 0) {
    			vx = -vx;
    			ball.move(vx, vy);	
    		}		
    	}
    	
    	private GObject getCollider() {
    		double ballX = ball.getX();
    		double ballY = ball.getY();
    		GObject collision = getElementAt(ballX, ballY);
    		if (collision == null) {
    			collision = getElementAt(ballX + BALL_RADIUS, ballY);
    			if (collision == null) {
    				collision = getElementAt(ballX, ballY + BALL_RADIUS);
    				if (collision == null) {
    					collision = getElementAt(ballX + BALL_RADIUS, ballY + BALL_RADIUS);
    				}
    			}
    		}
    		return collision;
    	}
    	
    	private void messageBox() {
    		double xPos = (getWidth() - boxWidth) / 2;
    		double yPos = (getHeight() - boxHeight) / 2;
    		messageBox = new GRect(xPos, yPos, boxWidth, boxHeight);
    		messageBox.setFilled(true);
    		messageBox.setFillColor(Color.BLUE);
    		add(messageBox);
    	}
    	
    	private void welcomeMessage() {
    		welcome.setColor(Color.WHITE);
    		click.setColor(Color.WHITE);
    		double welcomeHeight = welcome.getHeight();
    		double clickWid = click.getWidth();
    		double welcomeWid = welcome.getWidth();
    		double totalMessageHeight = welcomeHeight * 4;
    		double welcomeX = (messageBox.getX() + ((messageBox.getWidth() - welcomeWid) / 2));
    		double welcomeY = (messageBox.getY() + ((messageBox.getHeight() - totalMessageHeight) / 2));
    		double clickX = (messageBox.getX() + ((messageBox.getWidth() - clickWid) / 2));
    		double clickY = ((messageBox.getY() + ((messageBox.getHeight() - totalMessageHeight) / 2)) + welcomeHeight * 2);
    		add(welcome, welcomeX, welcomeY);
    		add(click, clickX, clickY);
    		pause(5000);
    		remove(click);
    		remove(welcome);
    		remove(messageBox);
    		playGame();
    	}
    	
    	
    	private void welcomeThePlayer() {
    		messageBox();
    		welcomeMessage();
    	}
    	
    	private void pointCounter() {
    		numPoints = 0;
    		score = new GLabel("Score: " + numPoints);
    		add(score, 5, (getHeight() - 5));
    	}
    	
    	private void changeScore(Color objectColor) {
    		int cyan = 25;
    		int green = 50;
    		int yellow = 75;
    		int orange = 100;
    		int red = 150;
    		if (objectColor == Color.CYAN) {
    			numPoints = numPoints + cyan;
    		} else if (objectColor == Color.GREEN){
    			numPoints += green;
    		} else if (objectColor == Color.YELLOW){
    			numPoints += yellow;
    		} else if (objectColor == Color.ORANGE){
    			numPoints += orange;
    		} else if (objectColor == Color.RED){
    			numPoints += red;
    		} else {
    			//do nothing
    		}
    		String newScore = ("Score: " + numPoints);
    		score.setLabel(newScore);
    	}
    	
    	private double rightPaddleBound;
    	private double lastY;
    	private double lastX;
    	private double vx, vy;
    	private RandomGenerator rgen = RandomGenerator.getInstance();	
    	private GRect paddle;
    	private GOval ball;
    	private int turnsRemaining;
    	private int numBricks;
    	private double boxHeight = 120;
    	private double boxWidth = 200;
    	private GRect messageBox;
    	private GLabel welcome;
    	private GLabel click;
    	private GObject killIt;
    	private GLabel score;
    	private int numPoints;
    }
    Last edited by Fubarable; 10-08-2011 at 10:12 PM. Reason: code tags added

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Breakout Assignment from CS106a

    Moderator Action: Code tags added to the post above to allow posted code to retain its formatting and be readable.

  3. #3
    Koala is offline Member
    Join Date
    Oct 2011
    Posts
    22
    Rep Power
    0

    Default Re: Breakout Assignment from CS106a

    The reason your score won't update is because you created your score label in one private method and are trying to change it in another.

    The line

    score = new GLabel("Score: " + numPoints);

    needs to go at the class level down at the bottom where you class level vars are, then you can manipulate those vars from within the changeScore method...

    Also, do you know you are loading the clip bounce.au every time the ball bounces? You need only load it once...
    I would put
    AudioClip bounceClip = MediaTools.loadAudioClip("bounce.au");
    at the class level too, then still call bounceClip.play() where you currently have it...
    Last edited by Koala; 10-09-2011 at 12:02 AM.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Breakout Assignment from CS106a

    Quote Originally Posted by Koala View Post
    The reason your score won't update is because you created your score label in one private method and are trying to change it in another.
    I'm not sure that this is the problem as the score variable is declared on the class level and so is visible throughout the program.

  5. #5
    Koala is offline Member
    Join Date
    Oct 2011
    Posts
    22
    Rep Power
    0

    Default Re: Breakout Assignment from CS106a

    Quote Originally Posted by Fubarable View Post
    I'm not sure that this is the problem as the score variable is declared on the class level and so is visible throughout the program.
    The variable yes, the label no. He is trying to update both the score variable and the text label that displays it in the changeScore() method.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Breakout Assignment from CS106a

    Quote Originally Posted by Koala View Post
    The variable yes, the label no. He is trying to update both the score variable and the text label that displays it in the changeScore() method.
    I'm not sure that I understand you. As long as the variable refers to a valid object, it doesn't matter if the assignment was done in a private method or in the class, as long as the assignment was done before the program tries to use the variable. Please clarify my misunderstanding on how his creating the GLabel variable in a private method should matter.
    Last edited by Fubarable; 10-09-2011 at 12:28 AM.

  7. #7
    tech8462 is offline Member
    Join Date
    Oct 2011
    Posts
    6
    Rep Power
    0

    Default Re: Breakout Assignment from CS106a

    I think I understand, you're saying that I need to actually create the string in the instance variable rather than the private method changeScore()?

  8. #8
    tech8462 is offline Member
    Join Date
    Oct 2011
    Posts
    6
    Rep Power
    0

    Default Re: Breakout Assignment from CS106a

    maybe not, I tried adding this to my instance variables. No luck...

    Java Code:
    private GLabel score = new GLabel("Score: " + numPoints);

  9. #9
    Koala is offline Member
    Join Date
    Oct 2011
    Posts
    22
    Rep Power
    0

    Default Re: Breakout Assignment from CS106a

    Well I'm not sure... not being able to get it to work on my end either... I wouldn't pass the brickColor variable itself to the changeScore() method though, I would create a seperate subclass for each type of brick and give each type a score attribute and a color attribute, then pass the score attribute to changeScore()

  10. #10
    tech8462 is offline Member
    Join Date
    Oct 2011
    Posts
    6
    Rep Power
    0

    Default Re: Breakout Assignment from CS106a

    Being new to java... I'm using eclipse helios, is there a way I can step through my code AND watch the variables change? I know how to step through but it would be useful to see the stack at the same time.

    What about passing a string with the name of the color instead of the color itself?

  11. #11
    Koala is offline Member
    Join Date
    Oct 2011
    Posts
    22
    Rep Power
    0

    Default Re: Breakout Assignment from CS106a

    Okay, figured it out. You are mixing up the brick's fill color with its color (not the same thing). In buildRow() you are setting each GRect's fill color to CYAN or RED or whatever. Then in bounceBall() you are using collider.getColor() to determine its color, but that gets its stroke color, which is always black. So you are passing black into the changeScore() method every time.

    The fix is, in your buildRow() method, add the line
    thisBrick.setColor(brickColor);
    right after you set the fill color.

    Attached Thumbnails Attached Thumbnails Breakout Assignment from CS106a-2mmephy.jpg  
    Fubarable and tech8462 like this.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

  13. #13
    tech8462 is offline Member
    Join Date
    Oct 2011
    Posts
    6
    Rep Power
    0

    Default Re: Breakout Assignment from CS106a

    Perfect. That worked like a charm. Thank you very much.

  14. #14
    Koala is offline Member
    Join Date
    Oct 2011
    Posts
    22
    Rep Power
    0

    Default Re: Breakout Assignment from CS106a

    yw :)

    some other constructive criticisms: It would be a good idea to set the size of the applet window so the user doesn't have to resize it at the beginning of the game to see the whole game, in your case since you're using the acm libraries you can do that with:

    public void init()
    {
    setSize(400,512);
    }

    above the run() method is usually a good spot.

    Also, try doing a find-and-replace and changing all instances of GRect to G3DRect, you might like the result :)

Similar Threads

  1. CS106A Stanford University
    By Learning Java in forum New To Java
    Replies: 116
    Last Post: 07-09-2011, 05:43 PM
  2. Breakout game in the assignment 3 cs106
    By dage in forum New To Java
    Replies: 5
    Last Post: 03-16-2011, 06:07 PM
  3. Stanford CS106A, my work- your thoughts?
    By chmza in forum New To Java
    Replies: 2
    Last Post: 12-02-2010, 06:53 PM
  4. Need help with Breakout game
    By tfitz666 in forum New To Java
    Replies: 9
    Last Post: 03-22-2010, 06:26 AM
  5. Another Breakout question
    By jumpstart in forum New To Java
    Replies: 3
    Last Post: 07-29-2009, 05:48 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •