// Whitaker Brand // CSE142 // Section BF // TA: Sarvagya // 1/22/2018 // This is an example program that we worked on in the A lecture, but not the B lecture. // It is some more drawing panel practice, and has some cumulative algorithm, and user // input aspects. // // It still could use some improvements: // - the inputs from the user are unnatural -- it asks what x displacement and y displacement // to use, it would be better to ask for an initial angle, and a displace in whatever direction // the ball is travelling. // - it doesn't have any method factoring, everything is in main. // - size of the ball should probably be a class constant // - collision detection with the wall needs some real work. We detect when the ball has collided with // the wall, and turn it around after that point, which is a poor model of what would happen in // in real life. // -- this is much too complicated for us to solve, though, and would involve making a simple physics // engine to answer questions like, how much speed does the ball lose to the collision, how // much does the ball compress when it hits the wall, etc. import java.awt.*; import java.util.*; public class Ball { public static void main(String[] args) { Scanner console = new Scanner(System.in); DrawingPanel panel = new DrawingPanel(1000, 1000); panel.setBackground(Color.YELLOW); Graphics pen = panel.getGraphics(); System.out.print("Please enter the x displacement: "); double xDisplacement = console.nextDouble(); // px System.out.print("Please enter the y displacement: "); double yDisplacement = console.nextDouble(); // px // store the x and y locations as a double, because the position of the ball // is really continuous, and we don't want to round the location earlier than // necessary double x = 500.0; double y = 500.0; // but cast the x and y locations to ints for the purposes of drawing, because // the Graphics object (pen) can't draw things at double locations. pen.fillOval((int) x, (int) y, 20, 20); for (int i = 1; i <= 200; i++) { // erase where the ball was pen.setColor(Color.YELLOW); pen.fillOval((int) x, (int) y, 20, 20); // change the x location of the ball // change the y location of the ball x = x + xDisplacement; y = y + yDisplacement; // draw the ball at the new location pen.setColor(Color.BLACK); pen.fillOval((int) x, (int) y, 20, 20); // turn around in th x direction if (x + 20 >= 1000 || x <= 0) { xDisplacement *= -1; } if (y <= 0 || y + 20 >= 1000) { yDisplacement *= -1; } panel.sleep(100); } } }