setup()
setup() runs once when the sketch starts. It's where you initialize the canvas, load external resources, and set up variables that won't change during the simulation. Notice that this sketch uses both p5.js functions (like createCanvas) and custom functions (like buildTrack) to organize the startup logic.
function setup() {
createCanvas(windowWidth, windowHeight);
trackSeed = random(10000);
speedSlider = select('#speedSlider');
newTrackBtn = select('#newTrackBtn');
newTrackBtn.mousePressed(() => {
trackSeed = random(10000);
generation = 1;
highestScore = 0;
genTimer = 0;
buildTrack();
initPopulation();
});
buildTrack();
initPopulation();
camX = startPos.x;
camY = startPos.y;
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a full-screen canvas that scales to the window size
trackSeed = random(10000);
Generates a seed number to ensure procedurally generated tracks are reproducible
newTrackBtn.mousePressed(() => { trackSeed = random(10000); generation = 1; highestScore = 0; genTimer = 0; buildTrack(); initPopulation(); });
Resets the simulation when user clicks 'Generate New Track' button
createCanvas(windowWidth, windowHeight);- Creates a canvas sized to fill the entire browser window, allowing full-screen visualization
trackSeed = random(10000);- Picks a random seed number between 0-10000 that will be used by Perlin noise to generate the track consistently
speedSlider = select('#speedSlider');- Grabs the HTML slider element so the code can read how fast the user wants the simulation to run
newTrackBtn.mousePressed(() => { ... });- Creates a callback function that runs whenever the user clicks the 'Generate New Track' button, resetting everything
buildTrack();- Generates the circular track with walls and checkpoints using Perlin noise
initPopulation();- Creates 120 new cars with random, nearly-zero neural network weights
camX = startPos.x;- Positions the camera at the starting checkpoint so you're looking at the race start