xxxxxxxxxx
71
let grid;
let selected = [];
function setup() {
createCanvas(400, 400);
grid = createRandomGrid(4, 4);
noLoop();
}
function draw() {
background(220);
displayGrid(grid);
}
function mousePressed() {
let x = floor(mouseX / width * 4);
let y = floor(mouseY / height * 4);
if (x >= 0 && x < 4 && y >= 0 && y < 4) {
selected.push({ x, y });
redraw();
}
}
function keyPressed() {
if (keyCode === ENTER) {
let word = getSelectedWord();
if (word.length > 0) {
console.log("Selected word:", word);
}
selected = [];
redraw();
}
}
function createRandomGrid(rows, cols) {
let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let grid = [];
for (let i = 0; i < rows; i++) {
let row = [];
for (let j = 0; j < cols; j++) {
let letter = letters[floor(random(letters.length))];
row.push(letter);
}
grid.push(row);
}
return grid;
}
function displayGrid(grid) {
let cellSize = width / grid[0].length;
textSize(32);
textAlign(CENTER, CENTER);
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
let x = j * cellSize + cellSize / 2;
let y = i * cellSize + cellSize / 2;
text(grid[i][j], x, y);
}
}
}
function getSelectedWord() {
let word = "";
for (let i = 0; i < selected.length; i++) {
let cell = selected[i];
word += grid[cell.y][cell.x];
}
return word;
}