/* * This program implements a 2D bouncing ball in the 2 x 2 square box * with center at the origin. * * Assume your CLASSPATH environment contains the path to stdlib.jar. * * Compilation: kotlinc -cp $CLASSPATH BouncingBall.kt * Execution: kotlin -cp $CLASSPATH BouncingBallKt * Dependencies: StdDraw and StdAudio * http://www.cs.princeton.edu/introcs/15inout/laser.wav * http://www.cs.princeton.edu/introcs/15inout/pop.wav * http://www.cs.princeton.edu/introcs/15inout/earth.gif * http://introcs.cs.princeton.edu/java/stdlib/stdlib.jar */ /* MAX_R is the maximum x- and y-coordinates of the bounding box. We'll set the minimum to -MAX_R. */ const val MAX_R = 1.0 // The following three numbers are gotten by trial and error. const val MIN_V = 0.005 // minimum velocity const val MAX_V = 0.015 // maximum velocity const val BALL_RADIUS = 0.03 // a hack since "earth.gif" is in pixels fun main(args: Array) { // set the scale of the coordinate system StdDraw.setScale(-MAX_R, MAX_R) // range of x-coordinate and y-coordinate of position val rRange = -MAX_R..MAX_R StdDraw.enableDoubleBuffering() var randGen = java.util.concurrent.ThreadLocalRandom.current() // pick a random starting position for the ball var rx = randGen.nextDouble(-MAX_R, MAX_R) // x-coordinate of position var ry = randGen.nextDouble(-MAX_R, MAX_R) // y-coordinate of position // pick a random starting velocity for the ball var vx = randGen.nextDouble(MIN_V, MAX_V) // x-coordinate of velocity var vy = randGen.nextDouble(MIN_V, MAX_V) // y-coordinate of velocity // main animation loop while (true) { // find the new position of the ball if (((rx + vx) + BALL_RADIUS) !in rRange) { vx = -vx StdAudio.play("laser.wav") } if (((ry + vy) + BALL_RADIUS) !in rRange) { vy = -vy StdAudio.play("pop.wav") } rx += vx ry += vy // clear the display buffer and draw the ball StdDraw.clear() StdDraw.picture(rx, ry, "earth.gif") // show the display buffer StdDraw.show() // show the buffer long enough to create animation in the viewer's mind StdDraw.pause(20) } }