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

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:

```&lt;pre&gt;

//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.

private GOval ball;

//ball set-up
private void drawBall() {
double x = getWidth()/2 - BALL_RADIUS;
double y = getHeight()/2 - BALL_RADIUS;
ball.setFilled(true);
}

private void playGame() {
waitForClick();
getBallVelocity();
while (true) {
moveBall();
}
}

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 &lt;= 0 &amp;&amp; vx &lt; 0 )|| (ball.getX() + vx &gt;= (getWidth() - BALL_RADIUS*2) &amp;&amp; vx&gt;0)) {
vx = -vx;
}
if ((ball.getY() - vy &lt;= 0 &amp;&amp; vy &lt; 0 ) || (ball.getY() + vy &gt;= (getWidth() - BALL_RADIUS*2) &amp;&amp; vy&gt;0)) {
vy = -vy;
}
}
&lt;/pre&gt;
```

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.