setup()
setup() runs once at the start. Here it does double duty: computing responsive layout math AND creating an HTML button via p5's DOM functions, showing how canvas drawing and regular DOM elements can coexist in the same sketch.
function setup() {
createCanvas(windowWidth, windowHeight);
// Calculate sizes based on the smaller dimension to fit on screen
let minDim = min(windowWidth, windowHeight);
padding = minDim * 0.05; // 5% padding
boardSize = minDim - 2 * padding;
tileSize = boardSize / gridSize;
initializeGrid();
// Create a button to shuffle/reset the game
shuffleButton = createButton('Shuffle');
shuffleButton.position(padding, padding + boardSize + 20); // Position below the board
shuffleButton.mousePressed(shuffleGrid); // Call shuffleGrid when button is pressed
shuffleButton.style('font-size', '24px');
shuffleButton.style('padding', '10px 20px');
shuffleButton.style('background-color', '#4CAF50'); // Green button
shuffleButton.style('color', 'white');
shuffleButton.style('border', 'none');
shuffleButton.style('border-radius', '5px');
shuffleButton.style('cursor', 'pointer');
}
Line-by-line explanation (10 lines)
createCanvas(windowWidth, windowHeight);- Makes the canvas fill the entire browser window.
let minDim = min(windowWidth, windowHeight);- Finds the smaller of width/height so the square board always fits on screen, even on tall or wide windows.
padding = minDim * 0.05;- Reserves 5% of the smaller dimension as empty margin around the board.
boardSize = minDim - 2 * padding;- The board itself is the smaller dimension minus padding on both sides.
tileSize = boardSize / gridSize;- Divides the board evenly into gridSize columns/rows to get each tile's pixel size.
initializeGrid();- Fills the grid array with numbers in solved order and marks the puzzle as solved.
shuffleButton = createButton('Shuffle');- Creates a real HTML button element (not drawn on canvas) using p5's DOM API.
shuffleButton.position(padding, padding + boardSize + 20);- Places the button just below the board using the same padding math as the board layout.
shuffleButton.mousePressed(shuffleGrid);- Registers shuffleGrid() to run whenever the button is clicked.
shuffleButton.style('background-color', '#4CAF50');- Uses CSS-in-JS style calls to give the button a green background, part of p5's DOM styling API.