xxxxxxxxxx
78
// Define global variables for images and game elements
let imgRedApple, imgRottenApple, imgTrashCan, imgBackground;
let trashCan;
let apples = [];
let redApplesCollected = 0; // Counter for collected red apples
let score = 0;
let gameOver = false; // Boolean to check if the game is over
// Preload images to ensure they are loaded before setup and draw
function preload() {
imgRedApple = loadImage('red.png');
imgRottenApple = loadImage('rotten.png');
imgTrashCan = loadImage('trash.png'); // Ensure this matches the file name exactly
// imgBackground = loadImage('background.png'); // Assuming a background image is used
}
// Setup the canvas and initial game settings
function setup() {
createCanvas(600, 600);
trashCan = new TrashCan(); // Initialize the trash can
textSize(32); // Set text size for score display
}
// Draw loop: runs continuously to render the game frames
function draw() {
if (!gameOver) {
// Display background and game elements
// image(imgBackground, 0, 0, width, height); // Display the background image
trashCan.display();
trashCan.move();
displayScore();
// Generate new apples periodically
if (frameCount % 60 === 0) {
let type = random(['clean', 'dirty']);
apples.push(new Apple(type));
}
// Update and display each apple
for (let i = apples.length - 1; i >= 0; i--) {
apples[i].move();
apples[i].display();
// Check for collisions with the trash can
if (apples[i].y + apples[i].size > trashCan.y && apples[i].x > trashCan.x && apples[i].x < trashCan.x + trashCan.width) {
if (apples[i].type === 'dirty') {
score += 10; // Increment score for rotten apples
} else {
redApplesCollected++; // Increment for red apples
if (redApplesCollected >= 5) {
gameOver = true; // End game if 5 red apples are collected
break; // Exit the loop since the game is over
}
}
apples.splice(i, 1); // Remove apple from array
} else if (apples[i].y > height) {
apples.splice(i, 1); // Remove apple if it falls off the screen
}
}
} else {
displayGameOver(); // Show game over screen if the game has ended
}
}
// Function to display the current score
function displayScore() {
fill(0); // Black color for text
textAlign(LEFT, TOP); // Align text to the top-left
text(`SCORE: ${score}`, 400, 50);
}
// Function to display the game over screen
function displayGameOver() {
background(0); // Set background to black
fill(255); // Set text color to white
textAlign(CENTER, CENTER); // Center the text
text('Game Over', width / 2, height / 2); // Display 'Game Over' message
}