Chance Operation
(for George Brecht)

The following code is a performance score presented at the Gallerie Stadt Sindelfingen on April 21, 2024.

It is a set of instructions for generating a piece of visual music via computer.

For best results, you can run the code by pasting the following at P5js.


let generateButton, dreamButton;
let pixelColor;
let currentX = 0;
let currentY = 0;
let isDreaming = false;
const canvasWidth = 640;
const canvasHeight = 480;

function setup() {
  createCanvas(canvasWidth, canvasHeight);
  background(255);

  // Create the 'Generate Pixel' button
  generateButton = createButton('Generate Pixel');
  generateButton.position(10, canvasHeight + 10);
  generateButton.mousePressed(generatePixel);

  // Create the 'Dream' button
  dreamButton = createButton('Dream');
  dreamButton.position(130, canvasHeight + 10);
  dreamButton.mousePressed(startDreaming);

  // Default pixel color
  pixelColor = color(0, 0, 0);
}

function generatePixel() {
  if (currentY < canvasHeight) {
    addPixel();
  } else {
    console.log("Canvas is full");
  }
}

function startDreaming() {
  isDreaming = true;
}

function addPixel() {
  // Generate a random number between 0 and 7
  let randomNumber = floor(random(8));

  // Map number to color
  if (randomNumber === 0 || randomNumber === 1) {
    pixelColor = color(0, 0, 255); // Blue
  } else if (randomNumber >= 2 && randomNumber <= 4) {
    pixelColor = color(0, 255, 0); // Green
  } else { // 5, 6, 7
    pixelColor = color(255, 0, 0); // Red
  }

  // Draw the pixel at the current position
  stroke(pixelColor);
  point(currentX, currentY);

  // Move to the next position
  currentX++;
  if (currentX >= canvasWidth) {
    currentX = 0;
    currentY++;
  }
}

function draw() {
  if (isDreaming && currentY < canvasHeight) {
    addPixel();
  } else if (isDreaming) {
    isDreaming = false;
    console.log("Dream completed. Canvas is full.");
  }
}