setup()
setup() runs once when the p5.js sketch starts. Use it to initialize your canvas, set up global variables, load resources, and prepare event listeners. In this game, it's where all the initial state is locked into place before the main game loop begins.
function setup() {
createCanvas(windowWidth, windowHeight);
noSmooth();
textFont('monospace');
initializeLayout();
initializePlayer();
populateBrainrots();
nextCelestialAt = millis() + celestialInterval;
scheduleNextWave(500);
window.addEventListener('blur', releaseAllKeys);
window.addEventListener('focus', releaseAllKeys);
}
Line-by-line explanation (9 lines)
createCanvas(windowWidth, windowHeight);- Creates a fullscreen canvas that fills the entire browser window, making the game responsive to window size.
noSmooth();- Disables anti-aliasing for a crisp, pixel-art-like appearance that fits the arcade aesthetic.
textFont('monospace');- Sets all text to monospace font, giving the UI a retro, code-like feel.
initializeLayout();- Calculates and stores positions of the base, safe areas, spawn line, and despawn line based on window dimensions.
initializePlayer();- Places the player character at the starting position (just below the base).
populateBrainrots();- Generates and scatters 70 brainrot creatures across the play area at random positions.
nextCelestialAt = millis() + celestialInterval;- Schedules the first special celestial brainrot to spawn after 5 minutes of play.
scheduleNextWave(500);- Schedules the first tsunami wave to spawn after 500 milliseconds, giving the player a brief moment to orient.
window.addEventListener('blur', releaseAllKeys);- Releases all movement keys when the window loses focus, preventing stuck movement if the player alt-tabs away.