function draw() {
background(25, 25, 50); // Dark blue background
if (gameState === 'playing') {
player.move();
player.show();
// Spawn enemies
if (frameCount % 60 === 0) { // Every second
let enemyName = random(['Anonymous', 'Corbyn', 'Corbyn 2.5']);
enemies.push(new Enemy(enemyName));
}
// Move and show enemies
for (let i = enemies.length - 1; i >= 0; i--) {
enemies[i].move();
enemies[i].show();
// Check if enemy hits player
if (player.hits(enemies[i])) {
gameState = 'gameOver';
if (gameOverSound) {
gameOverSound.start();
gameOverSound.amp(0.5, 0.1);
gameOverSound.amp(0, 0.5);
}
}
// Check if enemy goes offscreen
if (enemies[i].offscreen()) {
enemies.splice(i, 1);
// Game over if enemy passes player
gameState = 'gameOver';
if (gameOverSound) {
gameOverSound.start();
gameOverSound.amp(0.5, 0.1);
gameOverSound.amp(0, 0.5);
}
}
}
// Move and show projectiles
for (let i = projectiles.length - 1; i >= 0; i--) {
let projectileRemovedThisFrame = false; // Flag to track if the current projectile was removed
// Check if projectile hits enemy
for (let j = enemies.length - 1; j >= 0; j--) {
if (projectiles[i].hits(enemies[j])) {
score += 10; // Increase score
enemies.splice(j, 1); // Remove enemy
projectiles.splice(i, 1); // Remove projectile
projectileRemovedThisFrame = true; // Mark that it was removed
break; // Stop checking for this projectile against other enemies
}
}
// If the projectile was removed in the inner loop, skip the rest of this outer loop iteration
if (projectileRemovedThisFrame) {
continue; // Move to the next projectile in the outer loop
}
// Only move, show, and check offscreen if projectile was NOT removed by collision
projectiles[i].move();
projectiles[i].show();
// Check if projectile goes offscreen
if (projectiles[i].offscreen()) {
projectiles.splice(i, 1);
}
}
// Display score
fill(255);
textSize(20);
text('Score: ' + score, width / 2, 30);
} else if (gameState === 'gameOver') {
fill(255, 50, 50);
textSize(48);
text('GAME OVER', width / 2, height / 2 - 50);
textSize(24);
text('Final Score: ' + score, width / 2, height / 2 + 10);
text('Tap to Restart', width / 2, height / 2 + 60);
}
}