setup()
setup() runs once at sketch start and initializes all game state: canvas, world, entities, UI elements, and fonts. This is where you set up anything that should persist for the entire game session.
function setup() {
createCanvas(windowWidth, windowHeight);
worldGraphics = createGraphics(WORLD_WIDTH * TILE_SIZE, WORLD_HEIGHT * TILE_SIZE);
noiseSeed(floor(random(100000)));
initWorld();
spawnSkeletons();
spawnSpiders();
currentDay = 1;
textFont(minecraftFont);
restartButton = createButton('Play Again');
restartButton.style('font-size', '24px');
restartButton.style('padding', '15px 30px');
restartButton.style('background-color', '#4CAF50');
restartButton.style('color', 'white');
restartButton.style('border', 'none');
restartButton.style('border-radius', '8px');
restartButton.style('cursor', 'pointer');
restartButton.hide();
restartButton.mousePressed(resetGame);
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Sets up the display canvas to fit the window and creates an off-screen buffer for efficient world rendering
initWorld();
spawnSkeletons();
spawnSpiders();
Generates the procedural terrain, places initial enemies, and sets up the game world
createCanvas(windowWidth, windowHeight);- Creates a p5.js canvas that fills the browser window; allows fullscreen responsive design
worldGraphics = createGraphics(WORLD_WIDTH * TILE_SIZE, WORLD_HEIGHT * TILE_SIZE);- Creates an off-screen graphics buffer (6400×1920 pixels at 32px per tile) to draw the entire world once, then copy it efficiently each frame instead of redrawing all tiles
noiseSeed(floor(random(100000)));- Seeds the Perlin noise generator with a random number so each game generates a unique terrain
initWorld();- Builds the terrain array, places blocks, spawns the player, and draws the world to the graphics buffer
spawnSkeletons();- Creates the initial batch of skeleton enemies at random locations on solid ground
spawnSpiders();- Creates the initial batch of spider enemies at random locations on solid ground
textFont(minecraftFont);- Applies the loaded Press Start 2P font to all text drawn on the canvas
restartButton.hide();- Hides the restart button initially; it only appears when the game ends in WIN or LOSE state