> show canvas only <


/* built with Studio Sketchpad: 
 *   https://sketchpad.cc
 * 
 * observe the evolution of this sketch: 
 *   https://studio.sketchpad.cc/sp/pad/view/ro.pqAT$VHCvlg/rev.2043
 * 
 * authors: 
 *   Jim Bremner

 * license (unless otherwise specified): 
 *   creative commons attribution-share alike 3.0 license.
 *   https://creativecommons.org/licenses/by-sa/3.0/ 
 */ 



//Pressing control-R will render this sketch.
 
int frames = 60;
int ballNumber = 25;
int diameter = 10;
int colour = 350;
float e = 0.999; // coefficient of restitution
ballA[ballNumber] array = {};

void setup() { //this is run once.

    for (int i = 0; i < ballNumber; i++)        
    {
        array[i] = new ballA ((i % sqrt(ballNumber)) / sqrt(ballNumber)*400 + 50, (sqrt(ballNumber)*i / ballNumber) * 300, random(-2, 2), random(0, -2));
    }
 
    //set the background colour
    background(0);
    
    //canvas size (Integers only, please.)
    size(400, 400);
    
    //smooth edges
    smooth();
    
    //limit the number of frames per second
    frameRate(frames);
    
    //set the colour
    stroke(255, 255, 255, 100);
}
 
void draw() { //this is run repeatedly.
    background(0);

    for (int i = 0; i < ballNumber-1; i++)        
    {
        for (int j = i; j < ballNumber; j++)
        {
            ballA a = array[i];
            ballA b = array[j];
            
             if (a.xpos <= b.xpos+diameter && a.xpos >= b.xpos-diameter &&  a.ypos <= b.ypos+diameter && a.ypos >= b.ypos-diameter)
            {
                b.yspeed = -e*b.yspeed;
                b.xspeed = -e*b.xspeed;
                a.yspeed = -e*a.yspeed;
                a.xspeed = -e*a.xspeed;
                fill(700, 500, 100);
                if (b.xspeed*(-1) === -b.xspeed && a.speed*(-1) === -a.speed)
                {
                    b.xspeed = e*b.xspeed;
                }
            }
        }
    }
    
    for (int i = 0; i < ballNumber; i++)        
    {
        array[i].update();
    }
    
}

    class ballA 
{
    float xpos, ypos, xspeed, yspeed;
    
    ballA (float x, float y, float xs, float ys) 
    {
    xpos = x;
    ypos = y;
    xspeed = xs;
    yspeed = ys;
    }
    
    void update () 
    {
    ellipse(xpos,ypos,diameter,diameter);
    yspeed = yspeed + (9.8/frames);
    xpos = xpos + xspeed;
    ypos = ypos + yspeed;

    if (ypos >= 400 - (diameter / 2))
    {
        yspeed=-sqrt(sq(0.8*yspeed)); //Bounce off top and bottom
        ypos = 390;
    } 
    if (xpos >= 400-(diameter * 0.5))
    {     
        xspeed = -sqrt(sq(0.8*xspeed)); //Bounce off sides
    }
    if (xpos <= (diameter * 0.5))
    {
        xspeed =-0.8*xspeed;
    }
    if (xpos <= (diameter * 0.5))
    {     
        xpos = 10; 
    }
    if (xpos >= 400 - (diameter * 0.5))
    {     
        xpos = 390; 
    }
    }
}