# Random walker using Processing.JS on Khan Academy, with new walkers generated on mouse click

Posted on

Problem

I’ve created a project on Khan Academy as part of the Natural Simulations course on random walks.

This project is in JavaScript, using the Processing.JS library, slightly modified by Khan Academy.

(In the main, the inclusion of the Processing.JS library offers a few functions for drawing on a canvas. The majority of my project would be perfectly intelligible to someone who knew JavaScript but not about Processing.JS).

The code is as follows:

``````var Walker = function(colour, x, y) {
this.x = x || width/2; // 'width' and 'height' refer to the size of the canvas
this.y = y || height/2;
this.r = (colour[0] === 0)? true: colour[0] || random(0, 255);
this.g = (colour[1] === 0)? true: colour[1] || random(0, 255);
this.b = (colour[2] === 0)? true: colour[2] || random(0, 255);
return this;
};

// Randomly move up, down, left, right, or stay in one place
Walker.prototype.walk = function() {
var choice = floor(random(0, 4));
if (choice === 0 && this.x < width) {
this.x += this.radius; // move right
} else if (choice === 1 && this.x > 0) {
this.x -= this.radius; // move left
} else if (choice === 2 && this.y < height) {
this.y += this.radius; // move down
} else if (choice === 3 && this.y > 0) {
this.y -= this.radius; // move up
}
return this;
};

Walker.prototype.display = function() { // Processing.JS drawing stuff
noStroke(); // turn outline off
fill(this.r, this.g, this.b, 20); // fill(r, g, b, transparency);
return this;
};

var walkers = [new Walker([255, 0, 0])];

draw = function() { // repeats 30 times/second. Like a for/while loop, but slower
for(var i = 0; i < walkers.length; i++) {
walkers[i].walk().display();
}
};

mouseClicked = function() {
walkers.push(
}; // ^ mouseX/mouseY refer to current position of mouse on canvas
``````

View the project on Khan Academy.

I’m concerned about the performance of this code; specifically the `for` loop in the `draw` function. As the `draw` function repeats 30 times/second, will this mean that the loop will also repeat 30 times/second?

The program gets pretty slow when there’s quite a few walkers initiated. How can I make this program perform better?

Solution

I would put `noStroke` in a different location.

You are trying to make this code more efficient. You call `noStroke` each time one of these guys is called. You really only need to call it once right? So change the state once in your `draw` function:

``````draw = function() {
noStroke();
for(var i = 0; i < walkers.length; i++) {
walkers[i].walk().display();
}
};
``````

And remove it from your `Walker.display` function:

``````Walker.prototype.display = function() {
fill(this.r, this.g, this.b, 20);