xxxxxxxxxx
128
// // // Instructions
// * Click to change colour
// * Arrow Keys to move controllable block
// * Spacebar to jump to a random cell
// * 'r' to reset canvas
// * 'R' to randomize canvas
// // // Globals
let currX = 0;
let currY = 0;
let gridSize = 20;
let filled = [];
let mainColour = 'green'
// // // Screen Display
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// // Grid
stroke('grey');
for (let x = 0; x < width; x += gridSize) {
line(x, 0, x, height);
}
for (let y = 0; y < height; y += gridSize) {
line(0, y, width, y);
}
// // Traversed cells
for (let c = 0; c < filled.length; c++) {
fill(filled[c].colour);
rect(filled[c].x, filled[c].y, gridSize, gridSize);
}
// // Movable block
stroke('black');
fill(mainColour);
rect(currX, currY, gridSize, gridSize);
noStroke();
}
// // // Interaction
function mouseClicked() {
// // Change block colour on click
mainColour = color(random(255), random(255), random(255));
}
function keyPressed() {
// console.log(key);
switch(key) {
// // Move by one grid space on arrow key
case 'ArrowUp':
addCell(currX, currY);
currY -= gridSize;
checkPos();
break;
case 'ArrowDown':
addCell(currX, currY);
currY += gridSize;
checkPos();
break;
case 'ArrowLeft':
addCell(currX, currY);
currX -= gridSize;
checkPos();
break;
case 'ArrowRight':
addCell(currX, currY);
currX += gridSize;
checkPos();
break;
// // Spacebar = move to a random space
case ' ':
currX = randomCell(width);
currY = randomCell(height);
// console.log("Coords:", currX, currY);
break;
// // 'R' = populate grid w/ randomized cells
case 'R':
// // Clear existing cells if too large
if (filled.length > 5000) {filled.length = 0;}
// // Generate random cells (loosely based on grid dimensions)
for (let r = 0; r < (width/gridSize)*(height/gridSize); r++) {
let temp = new filledCell(randomCell(width), randomCell(height), color(random(255), random(255), random(255)));
filled.push(temp);
}
break;
// // 'r' = reset traversed cells
case 'r':
filled = [];
break;
// // Print unrecognized keys
default:
console.log(key);
}
}
// // // Helpers
// // Return a random value within bounds of grid
function randomCell(dimension) {
return round(random(dimension-gridSize)/gridSize)*gridSize;
}
// // Class for retaining pos/colour info of traversed cells
class filledCell {
constructor(x, y, colour) {
this.x = x;
this.y = y;
this.colour = colour;
}
}
// // Add a new cell instance to the relevant array
function addCell(oldX, oldY) {
let newC = new filledCell(oldX, oldY, mainColour);
filled.push(newC);
}
// // Check if new position is in bounds (for user movement)
function checkPos() {
// console.log("Checking:", currX, currY);
if (currX < 0) {currX = width - gridSize;} // check this
else if (currX > width - gridSize) {currX = 0;}
if (currY < 0) {currY = height - gridSize;} // check this
else if (currY > height - gridSize) {currY = 0;}
}