BouncingBall.java
Below is the syntax highlighted version of BouncingBall.java
from §2.4 Input and Output.
/*************************************************************************
* Compilation: javac BouncingBall.java
* Execution: java BouncingBall
* Dependencies: StdDraw.java
*
* Assumes the following files are in the same directory:
* earth.gif, laser.wav, pop.wav
*
* Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1).
*
* % java BouncingBall
*
*************************************************************************/
import java.awt.Color;
public class BouncingBall {
public static void main(String[] args) {
double rx = 0.480, ry = 0.860; // position
double vx = 0.015, vy = 0.023; // velocity
int SIZE = 512; // size of graphics window
StdDraw.create(SIZE, SIZE);
StdDraw.setScale(-1.0, -1.0, 1.0, 1.0);
while(true) {
StdDraw.clear(Color.black);
// detect collision with wall and reverse velocity
if (Math.abs(rx + vx) > 1.0) { vx = -vx; StdDraw.play("laser.wav"); }
if (Math.abs(ry + vy) > 1.0) { vy = -vy; StdDraw.play("pop.wav"); }
// update position
rx = rx + vx;
ry = ry + vy;
StdDraw.go(rx, ry);
StdDraw.spot("earth.gif");
StdDraw.pause(50);
}
}
}
Last updated: Wed Feb 9 18:29:01 EST 2005
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.