Example I.1
Traditional Random Walk
4 possible steps p5.js
8 possible steps includes the ninth to stay in the same place p5.js
Arbitrary random value between -1.0 and 1.0 p5.js
let w;
function setup() {
createCanvas(560,390);
background(255);
w = new Walker();
//create Walker obj by calling the constructor with the new operator
}
function draw() { //call functions on the Walker
w.step();
w.render();
//during each cycle through draw(), Walker will take a step and draw a dot
}
class Walker { //defince walker class
constructor() { //initialize obj
this.x = width/2;
//x location at the center of the canvas (obj's data)
this.y = height/2;
//y location at the center of the canvas (obj's data)
}
render() { //obj's 1st function: display itself as a dot
stroke(0);
point(this.x,this.y);
}
step() { //obj's 2nd function: direct walker obj to take a step
//4 possible steps
let choice = floor(random(4));
//random() returns a floating point between 0 (inclusive) and 4 (exclusive)
//floor() rounds a number downward to its nearest integer
//results will be 0, 1, 2, or 3
if (choice === 0) {
this.x++; //to right
} else if (choice == 1) {
this.x--; //to left
} else if (choice == 2) {
this.y++; //go down
} else {
this.y--; //go up
}
/* 8 possible steps includes the ninth to stay
let stepx = floor(random(3))-1; //pick from 3 possible steps along the x-axis (-1, 0, or 1)
let stepy = floor(random(3))-1; //pick from 3 possible steps along the y-axis (-1, 0, or 1)
this.x += stepx;
this.y += stepy;
*/
/* Arbitrary random value between -1.0 and 1.0
let stepx = random(-1, 1); //yields any floating point number between -1.0 and 1.0
let stepy = random(-1, 1); //yields any floating point number between -1.0 and 1.0
this.x += stepx;
this.y += stepy;
*/
this.x = constrain(this.x,0,width-1); //canvas width-1
this.y = constrain(this.y,0,height-1); //canvas height-1
//constrain(value, min, max)
//constrains a value to not exceed a max and min value
}
} //end of Walker class