xxxxxxxxxx
62
let rows;
let cols;
let boxSize = 100;
let arr = [];
let x;
let y;
function setup() {
createCanvas(400, 300);
rows = height/boxSize;
cols = width/boxSize;
x = int(random(0, cols));
y = int(random(0, rows));
for (let i=0; i<cols; i++){
arr[i] = [];
for (let j=0; j<rows; j++){
arr[i][j] = 0;
}
}
}
function draw() {
background(220);
let oldx = x;
let oldy = y;
x = constrain(x, 0, cols-1);
y = constrain(y, 0, rows-1);
arr[x][y] = 1; // Set value where box's index (x,y) to 1; the rest of the grid's values remain 0.
for (let i=0; i<cols; i++){
for (let j=0; j<rows; j++){
if (arr[i][j] == 1){
fill(255, 0, 0);
} else {
fill(255);
}
rect(i*boxSize, j*boxSize, boxSize, boxSize);
}
}
oldx = constrain(oldx, 0, cols-1);
oldy = constrain(oldy, 0, rows-1);
arr[oldx][oldy] = 0; // Set the previous location's value back to 0
}
function keyPressed(){
if (keyCode == LEFT_ARROW) {
x += -1;
} else if (keyCode == RIGHT_ARROW) {
x += 1;
} else if (keyCode == UP_ARROW) {
y += -1;
} else if (keyCode == DOWN_ARROW) {
y += 1;
}
}