movingball.java

来自「书籍"Java_面向事件编程"的附带光盘代码」· Java 代码 · 共 95 行

JAVA
95
字号
import objectdraw.*;public class MovingBall extends ActiveObject{    private static final int BALLSIZE = 30;    private static final int SCREENGAP = 130;        // Constants to determine ball speeds    private static final double MINSPEED = 0.08;    private static final double SPEEDRANGE = 0.15;    private static final int PAUSETIME = 33;        private FilledOval ball;        // components of speed vector    private double xspeed, yspeed, initYspeed;        // boundaries of playing area    private double bleft,bright,btop,offScreen;        // the paddle    private Rect paddle;        private RandomDoubleGenerator speedGen;    private DrawingCanvas canvas;        public MovingBall(DrawingCanvas aCanvas, Rect thePaddle,                      Rect boundary)    {        canvas = aCanvas;        paddle = thePaddle;                ball = new FilledOval(boundary.getLocation() ,                              BALLSIZE,BALLSIZE,canvas);        ball.move(1,1);                // pick random pixel/pause speeds        speedGen = new RandomDoubleGenerator(MINSPEED,SPEEDRANGE);        xspeed = speedGen.nextValue()-SPEEDRANGE/2;        if (xspeed > 0){            xspeed = xspeed + MINSPEED;        }        else {            xspeed = xspeed - MINSPEED;        }        yspeed = speedGen.nextValue() + MINSPEED;                initYspeed = yspeed;                // give names to boundary values        bleft = boundary.getX();        btop = boundary.getY();        bright = bleft + boundary.getWidth() - BALLSIZE;                offScreen = btop + boundary.getHeight() + SCREENGAP;                start();    }        public void run()    {        // used to record times and compute time between moves        double lastTime, currentTime, elapsedTime;                lastTime = System.currentTimeMillis();                while (ball.getY() < offScreen) {            // determine how much time has passed            currentTime = System.currentTimeMillis();            elapsedTime = currentTime - lastTime;            // restart timing            lastTime = currentTime;            ball.move(xspeed*elapsedTime,yspeed*elapsedTime);                        if ( ball.getX() < bleft  || ball.getX() > bright ) {                xspeed = -xspeed;            }                        if ( ball.getY() < btop ) {                yspeed = initYspeed;            } else if ( ball.overlaps(paddle) ) {                yspeed = -initYspeed;            }                        pause(PAUSETIME);        }        ball.removeFromCanvas();    }        }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?