
#include "ball.h"    // Include the definition of the class Ball
#include "wall.h"    // Include the definition of the class Wall:
                     //  it is required since various memebr functions of Wall 
                     //  are called from Ball's members  

void Ball::Move(){   // simple move
    Erase();
    x += vx;
    y += vy;
    Draw();
}

bool Ball::Collides( const Wall& w ){           
                                              
    // The ball is completely inside the rectangle
    // with upper-left  corner (x-radius, y-radius) and
    //      lower-right correr (x+radius, y+radius) 

    // Compute the next position of the ball and check if it intersects
    //  with the wall w.

    int nx = x + vx;  // next x and y 
    int ny = y + vy;

    return IntersectRects( w.Region(), MakeRect( nx-rad, ny-rad, nx+rad, ny+rad ) ); 
}

bool Ball::Collides( const Ball& b ){  

    // Treat the other ball as a fixed obstacle

    int nx = x + vx;  // next x and y 
    int ny = y + vy;

    return IntersectRects( b.Region() , 
                           MakeRect( nx-rad, ny-rad, nx+rad, ny+rad ) ); 
}

void Ball::Reflect( const Wall& w ){
    // Assume that the ball is about to collide, as detected by Collides(const Wall& ).
    // Figure on which side of the wall we are and change the velocities
    //   accordingly (simple reflection)
     
    Rect R = w.Region();

    // approaching the wall from left or right
    if( (x < R.left &&  vx > 0) || (x > R.right && vx < 0) )
        vx = w.ChangeSpeed(vx);
        
    // approaching the wall from above or below  
    if( (y < R.top && vy > 0) || (y > R.bottom && vy < 0) )
        vy = w.ChangeSpeed(vy);
}

void Ball::Reflect( const Ball& b ){
    // Assume that the ball is about to collide, as detected by Collides(const Ball& ).
    // Figure on which side of the wall we are and change the velocities
    //   accordingly (simple reflection)
     
    Rect R = b.Region();

    if( (x < R.left &&  vx > 0) || (x > R.right  && vx < 0) ) 
        vx = -vx;
    if( (y < R.top  && vy > 0)  || (y > R.bottom && vy < 0) )
        vy = -vy;
}

