Stanford CS106A Breakout Game Create A Ball And Get It To Bounce Off The Walls Solution

9 Nov

Wow, it feels good to have this part of the assignment down!! As I’m writing this, I’m watching the ball bounce around my Breakout window and now I know I’ll be able to finish this game!!! The instructions for this part of the assignment, creating a ball and getting it to bounce off the wall is as follows:

Here is my solution:

So my first attempt at this didn’t work out as planned. I think more about this part should be covered in class! After getting some help, I finally got something that makes sense! Here is what I came up with, which you can also find on gist:


//These are declared outside the method, but in the class.

/**Ball velocity*/
	private double vx, vy;

/**Random number generator for vx*/
	private RandomGenerator rgen = RandomGenerator.getInstance();

/** Animation delay or paust time between ball moves */
	private static final int DELAY = 10;

//this part is inside the method.

//adding an individual ball object
	private GOval ball;

//ball set-up
	private void drawBall() {
		double x = getWidth()/2 - BALL_RADIUS;
		double y = getHeight()/2 - BALL_RADIUS;
		ball = new GOval(x, y, BALL_RADIUS, BALL_RADIUS);

private void playGame() {
		while (true) {

private void getBallVelocity() {
		vy = 3.0;
		vx = rgen.nextDouble(1.0, 3.0);
		if (rgen.nextBoolean(0.5)) {
			vx = -vx;
private void moveBall() {
		ball.move(vx, vy);
		//check for walls
		//need to get vx and vy at the point closest to 0 or the other edge
		if ((ball.getX() - vx <= 0 && vx < 0 )|| (ball.getX() + vx >= (getWidth() - BALL_RADIUS*2) && vx>0)) {
			vx = -vx;
		if ((ball.getY() - vy <= 0 && vy < 0 ) || (ball.getY() + vy >= (getWidth() - BALL_RADIUS*2) && vy>0)) {
			vy = -vy;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s