In this p5.js code, I'm building a grid with a button that selects a random cell in the…
- User
In this p5.js code, I'm building a grid with a button that selects a random cell in the grid. In the code I've attached, please color the cell background red instead of there being an X drawn over the cell when the random button is pressed. Here is the code: const button = document.querySelector("button"); const cellSize = 50; const selectedCells = [];
function setup() { let canvas = createCanvas(7 * cellSize, 8 * cellSize, WEBGL); canvas.parent("sketch-holder"); }
function draw() { background(255); translate(-width / 2, -height / 2); drawGrid(); drawSelectedCells(); drawLabels(); }
function drawGrid() { for (let i = 0; i < 7; i++) { for (let j = 0; j < 8; j++) { stroke(0); noFill(); rect(i * cellSize, j * cellSize, cellSize, cellSize); } } }
// function drawSelectedCells() { // textSize(24); // fill(0); // textAlign(CENTER, CENTER); // for (const cell of selectedCells) { // const x1 = cell.col * cellSize + cellSize / 2; // const y1 = cell.row * cellSize + cellSize / 2;
// }
// }
function drawSelectedCells() { stroke(255, 0, 0); for (const cell of selectedCells) { let x1 = cell.col * cellSize; let y1 = cell.row * cellSize; line(x1, y1, x1 + cellSize, y1 + cellSize); line(x1, y1 + cellSize, x1 + cellSize, y1); // text("😀", x1, y1); } }
function selectRandomPosition() { if (selectedCells.length >= 7 * 8) { alert("All cells have been selected."); return; }
let col, row; do { col = floor(random(7)); row = floor(random(8)); } while (isSelected(col, row));
selectedCells.push({ col, row }); }
function isSelected(col, row) { return selectedCells.some(cell => cell.col === col && cell.row === row); }
function drawLabels() { textSize(20); fill(0); textAlign(CENTER, CENTER); for (let i = 0; i < 7; i++) { text(i + 1, i * cellSize + cellSize / 2 + 50, 25);
} for (let j = 0; j < 8; j++) { text(j + 1, 25, j * cellSize + cellSize / 2 + 50); } }
- Assistant
I've modified the drawSelectedCells() function to color the cell background red instead of drawing an 'X' over the cell when the random button is pressed. Here's the updated code:
js