This is a very simple topic, but it’s applications are endless. Thus, I thought it warranted a post. Randomness is something that is used everywhere in programming for simple simulations of dice rolls or more complex concepts such as initializing systems with a seed to produce consistent results. This post again uses P5js. Since the code is so simple, let’s just do a quick walk-through.
function setup() {
createCanvas(710, 400);
background(255);
strokeWeight(20);
frameRate(2);
}
function draw() {
for (var i = 0; i < width; i++) {
var r = random(150);
stroke(r);
line(i, 0, i, height);
}
}
This creates a canvas element with a white background and set’s the frame rate to be 2 – meaning it will only call the draw function twice per second. Every time the draw function is called, a new image will be displayed on the canvas so anything more than this would make it too difficult to see the results. The draw function creates a field of bars that go from the top of the canvas to the bottom with each one set to a different shade of gray.
Again, it is a very simple example of randomness, but the applications are endless. Most applications involve some sort of randomness so it is important for the average user to understand that their favorite applications and games are just a pseudo-random number generator determining the final outcome. Suddenly that “magic” seems a lot less impressive.
The code above can be found here with a running example.