setup()
setup() runs exactly once when the sketch loads. Use it to initialize the canvas, create your main objects, and load assets. Since loadImage is asynchronous, we pass callback functions (arrow functions with =>) that run when the image finishes loading or fails.
function setup() {
createCanvas(windowWidth, windowHeight);
player = new Player(width / 2, height - 80);
// Start with a few crabs
for (let i = 0; i < 8; i++) {
spawnCrab();
}
// Try to load the drop image (safe: not in preload)
loadImage(
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSdhQ-HYlAt8UQ83y38OKoFZmRzfqB9qgsTKg&s",
img => {
dropImg = img;
},
err => {
// If it fails (CORS/404), we just use a drawn gem instead
console.warn("Drop image failed to load, using fallback shape.", err);
}
);
}
Line-by-line explanation (6 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a canvas that fills the entire window for full-screen gameplay
player = new Player(width / 2, height - 80);
Creates the player character at the bottom center of the canvas
for (let i = 0; i < 8; i++) {
spawnCrab();
}
Populates the game with 8 starting crabs to challenge the player immediately
loadImage("https://...", img => { dropImg = img; }, err => { console.warn(...); });
Asynchronously loads a gem image for drops; uses a fallback shape if it fails
createCanvas(windowWidth, windowHeight);- Creates a canvas that matches your browser window size; this makes the game fullscreen and responsive
player = new Player(width / 2, height - 80);- Creates a new Player object at the horizontal center and near the bottom of the canvas (height - 80 pixels)
for (let i = 0; i < 8; i++) {- Loops 8 times to populate the starting wave of enemies
spawnCrab();- Calls spawnCrab() to add one new crab at a random edge of the screen
loadImage("https://...", img => { dropImg = img; }, ...- Attempts to load an image from a URL and stores it in dropImg if successful; the arrow function runs only when the image finishes loading
console.warn("Drop image failed to load, using fallback shape.", err);- If the image fails to load (due to network or CORS issues), this message prints to the console and the game uses a drawn cyan diamond instead