@nikhma99 — this looks really good!
I tried it out, and can’t really fault you on much. The example does exactly what it’s supposed to do. Well done!
@nikhma99 — this looks really good!
I tried it out, and can’t really fault you on much. The example does exactly what it’s supposed to do. Well done!
Hi Chris,
In the assessment, you wrote in the brief some lines which I couldn’t get a grasp of.
"You also need to add a new parameter to the new Ball() ( ... )
constructor call — the exists
parameter should be the 5th parameter, and should be given a value of true
. " ---- What did you mean by this ??
" Remember to set the Ball()
constructor’s prototype
and constructor
appropriately. " ---- By this line I get it what should be done, but you wrote this
" Ball.prototype.constructor = Ball; "
Why didn’t you use the " Object.defineProperty " ?
This was clearly mentioned in your articles but " Ball.prototype.constructor = Ball " property was not.
Hi Chris,
I’ll try to respond your questions from how I understood this assesment.
EvilCircle
, we somehow need to keep track of the fact whether a ball is “existant” or not. – that is why we defined the exists
property. And we also want to make sure that this property is assigned the value true
by default. So at every moment you create a new Ball
instance, you pass the value of true
as the constructor argument , and the constructor will set this.exists = true
of the Ball
.Object.defineProperty
is pretty much the same. So you can use either interchangeably I suppose. If you agree, you can put a +1 on my pull request https://github.com/mdn/learning-area/pull/131
I get it that ‘exists’ property is needed and it’s value should be ‘true’. That was done when we created a new Object instance of ‘Ball’ constructor and that argument was given the value ‘true’ as a third parameter. So my question is, while defining ‘Ball’ constructor, can we define this.exists = exists =true?
Because by this line:
You also need to add a new parameter to the new Ball() ( ... )
constructor call — the exists
parameter should be the 5th parameter, and should be given a value of true
.
I can only understand the above thing I mentioned.
Hello, I have just finished the ‘Adding features to our balls demo’, could anyone make some comments of my code? And I also put my answers to the bonus point questions in the code.
/*
my answers
* For a bonus point, let us know which keys the specified keycodes map to.
> 65 maps to A, 68 maps to D, 87 maps to W, and 83 maps to S. (ASCII code)
* For another bonus point, can you tell us why we've had to set let _this = this; in the position it is in? It is something to do with function scope.
> The `this` in `onkeydown` points to a different object than the `this` in `setControls`. (But I do not know which object the `this` in `onkeydown` points to, could you help with me?)
*/
// setup canvas
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
let width = canvas.width = window.innerWidth;
let height = canvas.height = window.innerHeight;
let paragraph = document.querySelector('p');
let ballCount = 0;
// function to populate paragraph
function countBall() {
paragraph.textContent = 'Ball count: ' + 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 = exists;
}
// define EvilCircle constructor
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);
Object.defineProperty(EvilCircle.prototype, 'constructor', {
value: EvilCircle,
enumerable: false,
writable: false
});
// define 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 evilcircle checkBounds method
EvilCircle.prototype.checkBounds = function() {
if ((this.x + this.size) >= width) {
this.x -= this.size;
}
if ((this.x - this.size) <= 0) {
this.x += this.size;
}
if ((this.y + this.size) >= height) {
this.y -= this.size;
}
if ((this.y - this.size) <= 0) {
this.y += this.size;
}
};
// define evilcircle setControls method
EvilCircle.prototype.setControls = function() {
let _this = this;
window.onkeydown = function(e) {
if(e.keyCode === 65)
_this.x -= _this.velX;
else if(e.keyCode === 68)
_this.x += _this.velX;
else if(e.keyCode === 87)
_this.y -= _this.velY;
else if(e.keyCode === 83)
_this.y += _this.velY;
}
};
// define 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;
}
}
};
// 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);
Object.defineProperty(Ball.prototype, 'constructor', {
value: Ball,
enumerable: false,
writable: true
});
// 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]) && 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].color = this.color = 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ')';
}
}
}
};
// define array to store balls and populate it
let balls = [];
while (balls.length < 25) {
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);
}
// create evil circle
let evilcircle = new EvilCircle(
random(20, width - 20),
random(20, height - 20),
true,
);
evilcircle.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);
evilcircle.draw();
evilcircle.checkBounds();
evilcircle.collisionDetect();
ballCount = 0;
for (let i = 0; i < balls.length; i++) {
if(balls[i].exists) {
balls[i].draw();
balls[i].update();
balls[i].collisionDetect();
++ballCount;
}
}
countBall();
requestAnimationFrame(loop);
}
loop();
@Tom-Vanderboom Hi there Tom, sorry for taking so long to reply to you on this.
I have tested your code, and looked over the answers, and everything looks very good. Well done!
Thank you for your reply. (I lost my github account so I have to create a new account to sign in. So this is me.)
But I still can not understand which object the this
in onkeydown
points to, could you give me a hint or something else?
OK, no worries
So, let’s talk through the this
question. We are talking about this block of code:
EvilCircle.prototype.setControls = function() {
let _this = this;
window.onkeydown = function(e) {
if(e.keyCode === 65)
_this.x -= _this.velX;
else if(e.keyCode === 68)
_this.x += _this.velX;
else if(e.keyCode === 87)
_this.y -= _this.velY;
else if(e.keyCode === 83)
_this.y += _this.velY;
}
};
The problem we have here is that we have a function inside a function (or a function inside a method if you want to nitpick), and this
is scoped to the function it is written inside.
So setControls
is a function set on the prototype of EvilCircle, therefore this
refers to whatever instance of EvilCircle you are creating and using in the code below, i.e. evilcircle
, when you do evilcircle.setControls();
later on.
But window.onkeydown = function(e) { ... }
also has its own this
. If we just called this
inside the anonymous function referred to above, this
would equal window
, and not evilcircle
.
We therefore have to set a separate custom variable, _this
equal to evilcircle
's this
, so that inside the window.onkeydown
function we can access the properties of evilcircle
we want to manipulate, such as x
and velX
.
Does that make sense? It’s a tricky part of JS.
Thank you very much, and I think I understand it. And sorry for taking so long to reply.
Hello everyone, I’ve just finished the " Creating our new objects" section and now all of the balls have disappeared and all I see is a black screen with the Bouncing Balls header. I believe I’ve followed the steps correctly so far but can someone tell me what I’m doing wrong here’s my code below:
// define shape constructor
function Shape(x, y, velX, velY, exists) {
this.x = x;
this.y = y;
this.velX = velX;
this.velY = velY;
this.exists = exists;
}
// define ball constructor
function Ball(x, y, velX, velY, exists, color, size){
Shape.call(this, x, y, velX, velY, exists)
this.size = size;
this.color = color;
}
Ball.prototype = Object.create(Shape.prototype);
Ball.prototype.constructor = Ball;
Hi @blairmclaughlin89, and welcome to the community.
I’m sorry to hear you are having trouble with the assessment on the OOJS module. It is one of the trickiest bits of the JavaScript language, so I think you can be forgiven a lot.
I think the best idea here might be for you to go through our final file, and see how it differs from yours? You find it here:
If after looking here you are still confused, maybe you could share your full code somewhere, and I’ll have a good look.
Best regards.
Hi @ericschwartz! This is a good question. Basically the answer is because the EvilCircle.prototype.collisionDetect = function() { ... }
block is defining a method that will exist on an instance of the EvilCircle class, when one is instantiated.
But this hasn’t happened yet. This code doesn’t really exist inside the global scope yet, in terms of it actually affecting anything, or being affected by anything.
This doesn’t happen until line 199:
var evil = new EvilCircle(random(0,width), random(0,height), true);
If you put line 177 somewhere below line 179, it would cause the code to fail.
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.
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.