"Adding features to our bouncing balls demo" assessment

This is a similar case to the method I asked about, as methods are a kind of function.

Yeah, methods are basically just functions that are available as object members.

I guess it’s all possible because of the way JavaScript is built; I assume other languages will check for the validity the code inside function definitions.

Yeah, other languages have a variety of levels of strictness in terms of this kind of thing. JavaScript is one of the slackest languages in this regard (and in other ways, e.g. dynamic data typing), but it is a strangth as well as a weakness, and there are features available if you want to make your code stricter (e.g. strict mode, and abstractions like TypeScript). I love JS because it gives you a lot of freedom.

Thanks for your help Chris, and thanks for teaching me web development on MDN! I will make companies out of my future apps one day and pay you back!

I am glad to be of help. And no need to pay me back — I just want to empower people and help them learn.

1 Like

Hi everyone! Whew! I finally got this to work.

Please, find my code below. Any feedback on what I should’ve done better is very much appreciated.

// setup canvas

let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');

let width = canvas.width = window.innerWidth;
let height = canvas.height = window.innerHeight;

// Ball count paragraph
let para = document.querySelector('#ballCount');

// function to generate random number

function random(min, max) {
  let num = Math.floor(Math.random() * (max - min)) + min;
  return num;
}

// define Shape constructor

function Shape(x, y, velX, velY, exists) {
  this.x = x;
  this.y = y;
  this.velX = velX;
  this.velY = velY;
  this.exists = Boolean;
}

// define Ball constructor

function Ball(x, y, velX, velY, exists, color, size) {
  Shape.call(this, x, y, velX, velY, exists);

  this.color = color;
  this.size = size;
}

Ball.prototype = Object.create(Shape.prototype);
Ball.prototype.constructor = Ball;

// define ball draw method

Ball.prototype.draw = function () {
  ctx.beginPath();
  ctx.fillStyle = this.color;
  ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
  ctx.fill();
};

// define ball update method

Ball.prototype.update = function () {
  if ((this.x + this.size) >= width) {
    this.velX = -(this.velX);
  }

  if ((this.x - this.size) <= 0) {
    this.velX = -(this.velX);
  }

  if ((this.y + this.size) >= height) {
    this.velY = -(this.velY);
  }

  if ((this.y - this.size) <= 0) {
    this.velY = -(this.velY);
  }

  this.x += this.velX;
  this.y += this.velY;
};

// define ball collision detection

Ball.prototype.collisionDetect = function () {
  for (let j = 0; j < balls.length; j++) {
    if (!(this === balls[j])) {
      let dx = this.x - balls[j].x;
      let dy = this.y - balls[j].y;
      let distance = Math.sqrt(dx * dx + dy * dy);

      if (distance < this.size + balls[j].size) {
        balls[j].color = this.color = 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ')';
      }
    }
  }
};

// define array to store balls and populate it

let balls = [];

let ballCount = 0;

while (balls.length < 30) {
  let size = random(10, 20);
  let ball = new Ball(
    // ball position always drawn at least one ball width
    // away from the adge of the canvas, to avoid drawing errors
    random(0 + size, width - size),
    random(0 + size, height - size),
    random(-7, 7),
    random(-7, 7),
    true,
    'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ')',
    size
  );
  balls.push(ball);
  ballCount++;
  para.innerHTML = `Ball count: ${ballCount}`;
}

// Define the EvilCircle() constructor inherited from Shape()

function EvilCircle(x, y, velX, velY, exists, color, size) {
  Shape.call(this, x, y, 20, 20, exists);

  this.color = 'white';
  this.size = 10;
}

EvilCircle.prototype = Object.create(Shape.prototype);
EvilCircle.prototype.constructor = EvilCircle;

// Define the EvilCircle() draw() method
EvilCircle.prototype.draw = function () {
  ctx.beginPath();
  ctx.lineWidth = 3;
  ctx.strokeStyle = this.color;
  ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
  ctx.stroke();
}

// Define the EvilCircle() checkBounds() method
EvilCircle.prototype.checkBounds = function () {
  if ((this.x + this.size) >= width) {
    this.x = -(this.x);
  }

  if ((this.x - this.size) <= 0) {
    this.x = -(this.x);
  }

  if ((this.y + this.size) >= height) {
    this.y = -(this.y);
  }

  if ((this.y - this.size) <= 0) {
    this.y = -(this.y);
  }
}

// Define the EvilCircle() setControls() method
EvilCircle.prototype.setControls = function () {
  let _this = this; // Reference the element responsible for 
  // firing the event handler
  window.onkeydown = function (e) {
    if (e.keyCode === 65) { // keycode 65 maps to 'A' – move left
      _this.x -= _this.velX;
    } else if (e.keyCode === 68) { // keycode 68 maps to 'D' – move right
      _this.x += _this.velX;
    } else if (e.keyCode === 87) { // keycode 87 maps to 'W' – move up
      _this.y -= _this.velY;
    } else if (e.keyCode === 83) { // keycode 68 maps to 'S' – move down
      _this.y += _this.velY;
    }
  }
}

// Define the EvilCircle() collisionDetect() method
EvilCircle.prototype.collisionDetect = function () {
  for (let j = 0; j < balls.length; j++) {
    if (balls[j].exists) {
      let dx = this.x - balls[j].x;
      let dy = this.y - balls[j].y;
      let distance = Math.sqrt(dx * dx + dy * dy);

      if (distance < this.size + balls[j].size) {
        balls[j].exists = false;
        // Decrement the ball count
        ballCount--;
        // Display the updated number of balls
        para.innerHTML = `Ball count: ${ballCount}`;
      }
    }
  }
}

// Create a new evil ball object instance from EvilCircle()

let evilBall = new EvilCircle(random(0, width), random(0, height), true);

// Set evillBall controls once

evilBall.setControls();

// define loop that keeps drawing the scene constantly

function loop() {
  ctx.fillStyle = 'rgba(0,0,0,0.25)';
  ctx.fillRect(0, 0, width, height);

  for (let i = 0; i < balls.length; i++) {
    if (balls[i].exists) {
      balls[i].draw();
      balls[i].update();
      balls[i].collisionDetect();
      evilBall.draw();
      evilBall.checkBounds();
      evilBall.collisionDetect();
    }
  }

  requestAnimationFrame(loop);
}

loop();

Hi @samuel — thanks for sending this in, and congratulations, this looks like it works perfectly. Your code looks good, and you’ve used updated let keywords instead of var, which is great.

The only thing I’d say about that is that you could probably use const instead of let for declaring variables that are never going to change value, like canvas or ctx. But that’s a relatively minor point compared to everything else.

This is one of the hardest assessments we’ve got, so you should feel proud.

Hi everyone,
everything works fine with my code, except the evil.collisionDetect function.
When a ball touch the evil nothing happend.
Pease find my code below, any help or suggestion will be welcome!!
I spent the whole last night to try to find my error…unsuccessfull!!
(sorry for my english).
My code :

// setup canvas

var canvas = document.querySelector(‘canvas’);
var ctx = canvas.getContext(‘2d’);

var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;
var compteur = document.querySelector (‘p’);
var count = 0;

// function to generate random number

function random(min,max) {
var num = Math.floor(Math.random()*(max+1-min)) + min;
return num;
}

function Shape(x, y, velX, velY, exists){
this.x = x;
this.y = y;
this.velX = velX;
this.velY = velY;
this.exists = exists;
}

function Ball(x, y, velX, velY, exists, color, size){
Shape.call(this, x, y, velX, velY, exists);
this.color = color;
this.size = size;
}

Ball.prototype = Object.create(Shape.prototype);
Ball.prototype.constructor = Ball;

function EvilCircle(x, y, exists){
Shape.call(this, x, y, 20, 20, exists);
this.color = ‘white’;
this.size = 10;
}

EvilCircle.prototype = Object.create(Shape.prototype);
EvilCircle.prototype.constructor = EvilCircle;

Ball.prototype.draw = function() {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
ctx.fill();
}

Ball.prototype.update = function() {
if ((this.x + this.size) >= width){
this.velX = -(this.velX);
}

if ((this.x - this.size) <= 0){
	this.velX = -(this.velX);
}

if ((this.y + this.size) >= height) {
this.velY = -(this.velY);

}

if ((this.y - this.size) <= 0) {
this.velY = -(this.velY);
}

this.x += this.velX;
this.y += this.velY;

}

EvilCircle.prototype.checkBounds = function() {
if ((this.x + this.size) >= width){
this.x = (width - this.size);
}

if ((this.x - this.size) <= 0){
this.x = this.size;
}

if ((this.y + this.size) >= height) {
this.y = (height - this.size);
}

if ((this.y - this.size) <= 0) {
this.y = this.size;
}

}

EvilCircle.prototype.setControls = function() {
var _this = this;
window.onkeydown = function(e) {
if (e.keyCode === 37) {
_this.x -= _this.velX;
} else if (e.keyCode === 39) {
_this.x += _this.velX;
} else if (e.keyCode === 38) {
_this.y -= _this.velY;
} else if (e.keyCode === 40) {
_this.y += _this.velY;
}
}
}

Ball.prototype.collisionDetect = function() {
for (var j = 0; j < balls.length; j++) {
if (!(this === balls[j])) {
var dx = this.x - balls[j].x;
var dy = this.y - balls[j].y;
var distance = Math.sqrt(dx * dx + dy * dy);

  if (distance < this.size + balls[j].size) {
    balls[j].color = this.color = 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) +')';
  }
}

}
};

EvilCircle.prototype.collisionDetect = function() {
for (var j = 0; j < balls.length; j++) {
if (balls[j].exists = true) {
var dx = this.x - balls[j].x;
var dy = this.y - balls[j].y;
var distance = Math.sqrt(dx * dx + dy * dy);

  if (distance < this.size + balls[j].size) {
    balls[j].exists = false;
    count--;
  }
}

}
};

EvilCircle.prototype.draw = function() {
ctx.beginPath();
ctx.lineWidth = 3;
ctx.strokeStyle = this.color;
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
ctx.stroke();
};

var balls = [];

var viseur = new EvilCircle(
random(0,width),
random(0,height),
20,
20,
true);
viseur.setControls();

function loop() {
ctx.fillStyle = ‘rgba(0, 0, 0, 0.5)’;
ctx.fillRect(0, 0, width, height);

while (balls.length < 15) {
var ball = new Ball(
random(0,width),
random(0,height),
random(-7,7),
random(-7,7),
true,
‘rgb(’ + random(0,255) + ‘,’ + random(0,255) + ‘,’ + random(0,255) +’)’,
random(10,20)
);
balls.push(ball);
count++;
};

viseur.draw();
viseur.collisionDetect();
viseur.checkBounds();

for (var i = 0; i < balls.length; i++) {
if (balls[i].exists = true){
balls[i].draw();
balls[i].update();
balls[i].collisionDetect();
}
}

requestAnimationFrame(loop);
}

loop();

compteur.textContent += (count);

Hi @tahar.bouhadida!

I have had a quick look, and I’m not immediately sure what si wrong. All the differnt components you need seem to be there.

Our version of the code is here:

Try looking at it and seeing how it differs from yours, and if you can trakc down the problem.

If not, let me know and I’ll have another look.

Hi Chrismills,
and thank you for you answer.
I compared my code with the solution you showed me and everything seems to be correct, except the order I declared the prototypes, but I think it doesn’t have any impact (??).
I have also some change to made on the balls count display, but it have nothing to do with collisionDetect.
I would be very gratefull if you can help me finding the wrong thing I did.
Best regards.

Awesome assessment! I really enjoyed it. Would have loved if the balls could bounce off each other, but I guess it’s really too complicated.

I found a small detail, that wasn’t described in the steps. The collissionDetect function of the balls currently still detects collisions with non-existing balls. This can be fixed by changing the condition in the if statement to if (!(this === balls[j]) && balls[j].exists) so the ball changes only color if it hits an existing ball.

And one question. I wanted to replace the window.onclick = function(e) {...}; event handler by window.addEventListener('onclick', function(e) {...}); to be able to later delete this event handler when the game finishes, so the user can’t move the evil circle anymore. But it won’t work with the addEventListener method. I also tried it on the document instead of on the window without any luck. My code is otherwise similar to the solution code.

@gerfolder cool, I’m glad you enjoyed the assessment. It wouldn’t be too hard to program balls that bounce off one another rather than change color; you could just do something similar to the code that makes them bounce off the edges of the screen. Making it work realistically in most situations would be the real challenge!

I decided to keep it simpler with the color change code, as I thought it was getting involved enough already, plus I thought the color change idea was kind cute.

About the collisionDetect() function of the balls — I suspect we solved this in a slightly different way. My function looks like this:

Ball.prototype.collisionDetect = function() {
  for(var j = 0; j < balls.length; j++) {
    if(!(this === balls[j])) {
      var dx = this.x - balls[j].x;
      var dy = this.y - balls[j].y;
      var distance = Math.sqrt(dx * dx + dy * dy);

      if (distance < this.size + balls[j].size && balls[j].exists) {
        balls[j].color = this.color = 'rgb(' + random(0,255) + ',' + random(0,255) + ',' + random(0,255) +')';
      }
    }
  }
};

So I am detecting to make sure we are not trying to detect a collision between the ball and itself, then I am detecting the collision but also detecting whether the ball exists in a separate if statement. It might make more sense to move the exists bit up to the first if statement…?

As for the event listener code, I wonder if you are finding a problem with this because of function scope - the keydown handler is being set inside the setControls() method, so it won’t exist outside of that function? If you defined the keydown handler in the global scope, then referenced it from there, would that work?

@chrisdavidmills Thanks, I will try to implement the bouncing balls. I am just thinking how to figure out the direction to which the balls bounce of. Because with the stationary wall it was easy to just reverse the velocity of a ball, but with two balls bouncing in each other the direction is always different.

Regarding the collisionDetect() function: Ups, I didn’t spot the && balls[j].exists in the second if statement in the solution code. I put it in the first. I think it makes more sense to put it in the first, because if a ball doesn’t exists and is hidden it makes no sense to compute the distances anymore and one could save a bit on computation.

I tried putting the event handler outside, but it didn’t work. Also in my answer above I mistakenly wrote ‘onclick’ when it should be ‘onkeydown’. I can’t edit it anymore but I have been using ‘onkeydown’ in my code, so that is not the problem.

EDIT: Ok, I found the relevant math and it’s actually fairly easy. If you assume they all have the same mass they just exchange their velocities upon collision. I just replaced the line

balls[j].color = this.color = 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ')';

with

const tmpVelX = this.velX;
const tmpVelY = this.velY;
this.velX = balls[j].velX;
this.velY = balls[j].velY;
balls[j].velX = tmpVelX;
balls[j].velY = tmpVelY;

But it’s not perfect though. Sometimes they remain stuck together after a collision and also if they happen to be generated on top of each other they will be stuck together. And if they collide close to the wall they may push each other inside the wall and then get stuck there. I suppose the velocities don’t get updated fast enough because of some computation inefficiencies or slow animation rate.