
#include "ct_emu.h"

#include "utils.h"
#include "ball.h"
#include "wall.h"
        
// Check for intersection of two rectangles. 
// Return true if they intersect, false otherwise.

bool IntersectRects( const Rect& r1, const Rect& r2 ){
    return ! ( r1.bottom < r2.top  ||
		       r2.bottom < r1.top  ||
		       r1.right  < r2.left ||
		       r2.right  < r1.left  );
}

const int NUM_WALLS = 6;
const int NUM_BALLS = 5;

int main(){

    BigSquarePair();

    SetRandomSeed();   // set current time as the random seed
  
    // set and draw the border walls
    Wall w[ NUM_WALLS ];  // This calls the  Wall::Wall()  default 
                          //   constructor NUM_WALLS times. Unfortunately,
                          //   there is no way to pass args at this time.

    // black (default) normal (default) border walls
    w[0] = Wall( MakeRect( 50, 50, 350, 60   ) );        
    w[1] = Wall( MakeRect( 50, 350, 360, 360 ) );
    w[2] = Wall( MakeRect( 50, 60, 60, 360   ) );
    w[3] = Wall( MakeRect( 350, 50, 360, 360 ) );
    // red accelerating wall
    w[4] = Wall( MakeRect( 150, 100, 250, 130 ), 1.5, 255, 0, 0 ); 
    // blue decelerating wall
    w[5] = Wall( MakeRect( 150, 270, 250, 300 ), 0.75, 0, 0, 255 );

    // draw the walls
    SetForeColor(0,0,0);
    for(int i=0; i <  NUM_WALLS; i++ )
    	w[i].Draw();
           
    Ball b[ NUM_BALLS ];

    // Task II:
    // verify the placement of the balls. Re-generate if there are overlaps.

    for(int n=0; n < NUM_BALLS; n++ ){ // for each ball
        // check n-th ball against all walls
        int i=0;                // the index of the wall being checked
        while( i < NUM_WALLS ){
            if( IntersectRects( b[n].Region(), w[i].Region() ) ){
                b[n].Reset();  // re-generate the ball
                i = 0;          // ..and start checking from 0-th wall all over
            }
            else
                i++;            // this wall is OK, check the next one
        }
    }

    // main simulation loop
    for(int t=0; t<1000; t++){  // time
        for( int j=0; j < NUM_BALLS; j++ ){  // for each ball

            // check for collisions with other balls (hence j != l below)
            for( int l=0; l < NUM_BALLS; l++ ) 
                if( j != l && b[j].Collides( b[l] ) ) 
                	b[j].Reflect(  b[l] );

   
            // check for collisions with walls
        	for( int k=0; k < NUM_WALLS; k++ )
            	if( b[j].Collides( w[k] ) ) 
                	b[j].Reflect(  w[k] );
        
            b[j].Move();
            
        }
        Delay(50);
        // DEBUG:  wait for a mouse click before advancing to the next tick
        // Point dummy;
        // GetClickPoint( dummy );
    }

    PressReturn();

    return 0;
}

 

