setup()
setup() runs once when the sketch starts. It prepares the canvas, creates HTML UI elements, and initializes game state. Notice how forEach() creates multiple buttons from the weapons array in a loop instead of writing each button manually.
function setup() {
createCanvas(900, 600);
// Conteneur des boutons
uiContainer = createDiv();
uiContainer.id('ui-container');
// Boutons d'armes
weapons.forEach((w, i) => {
const btn = createButton(w.name);
btn.parent(uiContainer);
btn.addClass('weapon-button');
if (i === currentWeaponIndex) btn.addClass('active');
btn.mousePressed(() => selectWeapon(i));
weaponButtons.push(btn);
});
// Bouton reset
const resetBtn = createButton('Réinitialiser Buddy (R)');
resetBtn.parent(uiContainer);
resetBtn.id('reset-btn');
resetBtn.addClass('weapon-button');
resetBtn.mousePressed(resetBuddy);
resetBuddy();
}
Line-by-line explanation (5 lines)
🔧 Subcomponents:
weapons.forEach((w, i) => {
Creates three weapon selection buttons, one for each weapon in the weapons array
resetBuddy();
Spawns the buddy character with full health and resets all game state
createCanvas(900, 600);- Creates a 900-pixel-wide by 600-pixel-tall canvas where the game will be drawn
uiContainer = createDiv();- Creates an HTML div element to hold the weapon buttons below the canvas
weapons.forEach((w, i) => {- Loops through each weapon object in the weapons array to create a button for each one
btn.mousePressed(() => selectWeapon(i));- Attaches a click handler to each button so clicking it calls selectWeapon() with that weapon's index
resetBuddy();- Initializes the buddy object with full health at the center of the canvas