# 投稿記事

## ProcessingJS 勉強 - Random walker

14 Jun 2016

Randomness

function sketchProc(processing) {

var height = 500,
width = 500;
var stepSize = 3;

/*-------
Walker Object
*/
var Walker = function() {
this.x = width/2;
this.y = height/2;
processing.noStroke();
};
// display method
Walker.prototype.display = function() {
//  processing.stroke(0, 0, 0);
processing.fill(Math.floor(processing.random(256)),
Math.floor(processing.random(256)),
Math.floor(processing.random(256)));
};
// walk method
Walker.prototype.walk = function() {
var choice = Math.floor(processing.random(8));
if (choice === 0) {
this.x += stepSize;
} else if (choice === 1) {
this.x -= stepSize;
} else if (choice === 2) {
this.y += stepSize;
} else if (choice === 3){
this.y -= stepSize;
} else if (choice === 4){
this.x += stepSize;
this.y += stepSize;
} else if (choice === 5){
this.x += stepSize;
this.y -= stepSize;
} else if (choice === 6){
this.x -= stepSize;
this.y += stepSize;
} else {
this.x -= stepSize;
this.y -= stepSize;
}
};

// Walker instance
var w = new Walker();
// setup
processing.setup = function(){
// canvas size
processing.size(width,height);
};
// draw
processing.draw = function() {
w.walk();
w.display();
};

};

モンテカルロ法

function sketchProc2(processing) {

var height = 500,
width = 500;
var stepSize = 3;

// Generates random numbers using the Monte Carlo Method
var monteCarlo = function() {
while (true) {
var r1 = processing.random(1);
var probability = r1;
var r2 = processing.random(1);
if (r2 < probability) {
return r1;
}
}
};

/*-------
Walker Object
*/
var Walker = function() {
this.x = width/2;
this.y = height/2;
processing.noStroke();
};
// display method
Walker.prototype.display = function() {
//  processing.stroke(0, 0, 0);
processing.fill(Math.floor(processing.random(256)),
Math.floor(processing.random(256)),
Math.floor(processing.random(256)));
};
// walk method
Walker.prototype.walk = function() {
var stepSize = monteCarlo() * 10;

var xStepSize = processing.random(-stepSize, stepSize);
var yStepSize = processing.random(-stepSize, stepSize);

this.x += xStepSize;
this.y += yStepSize;
};

// Walker instance
var w = new Walker();
// setup
processing.setup = function(){
// canvas size
processing.size(width,height);
};
// draw
processing.draw = function() {
w.walk();
w.display();
};

};