xxxxxxxxxx
96
let w = 100;
let cols, rows;
let selected = null;
class Cell {
constructor(x, y) {
this.x = x;
this.y = y;
this.clr = color(random(255), random(255), random(255));
this.empty = false;
this.selected = false;
}
show() {
if (this.empty) {
fill(240);
strokeWeight(1);
stroke(127);
rect(this.x, this.y, w);
} else {
fill(this.clr);
if (this.selected) {
stroke(255, 0, 0);
strokeWeight(4);
} else {
strokeWeight(1);
stroke(0);
}
rect(this.x, this.y, w);
}
}
}
let cells = [];
function mousePressed() {
let col = floor(mouseX / w);
let row = floor(mouseY / w);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
cells[i][j].selected = false;
}
}
if (col >= 0 && col < cols && row >= 0 && row < rows) {
cells[col][row].selected = true;
selected = cells[row][col];
}
}
function keyPressed() {
if (!selected) return;
let x = selected.x;
let y = selected.y;
let col = floor(x / w);
let row = floor(y / w);
if (keyCode == DOWN_ARROW) {
if (cells[col][row + 1].empty) {
let temp = cells[col][row + 1];
cells[col][row + 1] = cells[col][row];
cells[col][row] = temp;
}
}
if (keyCode == RIGHT_ARROW) {
if (cells[col+1][row].empty) {
let temp = cells[col][row + 1];
cells[col][row + 1] = cells[col][row];
cells[col][row] = temp;
}
}
}
function setup() {
createCanvas(400, 400);
cols = width / w;
rows = width / w;
for (let i = 0; i < cols; i++) {
cells[i] = [];
for (let j = 0; j < rows; j++) {
cells[i][j] = new Cell(i * w, j * w);
}
}
cells[cols - 1][rows - 1].empty = true;
}
function draw() {
background(220);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
cells[i][j].show();
}
}
}