using System; using System.Drawing; using System.Collections; /// ///object to be animated for the Balls program /// public class Ball { public Color color; public int x,y; // position of center public int p,q; // x and y velocities; public int r; // radius of ball public int mass; // needed if we someday want to make the balls collide with each other public Ball(Color c, int X, int Y, int xVelocity, int yVelocity, int radius) { color = c; x = X; y = Y; p = xVelocity; q = yVelocity; r = radius; } public void Draw(Graphics g) { Brush b = new SolidBrush(color); Rectangle rect = new Rectangle(x-r, y - r, 2*r,2*r); g.FillEllipse(b,rect); } public void Bounce(int t, Rectangle box) { // update position and velocity, including bouncing off the walls of box x = (int)(x + p*t/1000.0F); y = (int)(y + q*t/1000.0F); int oops = x + r - box.Right; if(oops > 0) { x -= oops; // bounce off right wall p = -p; } oops = r - x; if(oops > 0) { x += oops; p = -p; } oops = y + r - box.Bottom; if(oops> 0) { y -= oops; q = -q; } oops = r-y; if(oops > 0) { y += oops; q = -q; } } /* A challenge to my A+ students: Implement this and make the balls bounce off of each other as well as the walls */ private void Collide(ref Ball u, ref Ball v) { int M = u.mass; int m = v.mass; } public static void UpdateBalls(ArrayList balls, int t, Rectangle box) // update positions and velocities of all the balls to // reflect the passage of time t (in milliseconds) { foreach(Ball b in balls) { b.Bounce(t,box); } } }