/****************************************************************************** * Compilation: javac DeluxeBouncingBall.java * Execution: java DeluxeBouncingBall * Dependencies: StdDraw.java StdAudio.java * https://introcs.cs.princeton.edu/java/15inout/BallTap.wav * https://introcs.cs.princeton.edu/java/15inout/BlockHit.wav * https://introcs.cs.princeton.edu/java/15inout/TennisBall.png * * Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1). * * % java DeluxeBouncingBall * * Credits: BallTap.wav and BlockHit.wav are from * https://mixkit.co/free-sound-effects/game/ * Free for educational use under the Mixkit Sound Effects Free License. * https://mixkit.co/license/#sfxFree * ******************************************************************************/ public class DeluxeBouncingBall { public static void main(String[] args) { double rx = 0.480, ry = 0.860; // position double vx = 0.015, vy = 0.023; // velocity double radius = 0.03; // a hack since "earth.gif" is in pixels // set the scale of the coordinate system StdDraw.setXscale(-1.0, 1.0); StdDraw.setYscale(-1.0, 1.0); StdDraw.enableDoubleBuffering(); // main animation loop while (true) { if (Math.abs(rx + vx) + radius > 1.0) { vx = -vx; StdAudio.playInBackground("BallTap.wav"); } if (Math.abs(ry + vy) + radius > 1.0) { vy = -vy; StdAudio.playInBackground("BlockHit.wav"); } rx = rx + vx; ry = ry + vy; StdDraw.clear(); StdDraw.picture(rx, ry, "TennisBall.png"); StdDraw.show(); StdDraw.pause(20); } } }