
Here’s a detailed description of how the game works, along with comments on the JavaScript code:
Detailed Code Analysis with Comments
const canvas = document.getElementById(‘gameCanvas’);
const cubo = document.getElementById(‘cubo’);
const scoreBoard = document.getElementById(‘scoreBoard’);
const timerDisplay = document.getElementById(‘timer’);
// Array of trash images for random selection
const basuraImages = [
‘images/basura1.webp’,
‘images/basura2.webp’,
‘images/basura3.webp’,
‘images/basura4.webp’,
‘images/basura5.webp’
];
// Game state variables
let score = 0; // Tracks the player’s score
let timeLeft = 300; // Total game time in seconds (5 minutes)
let gameInterval; // Interval for the game timer
// Function to create a trash item at a random position
function createTrash() {
const trash = document.createElement(‘div’); // Create a new HTML element
trash.classList.add(‘object’); // Assign it the ‘object’ class
const randomImage = basuraImages[Math.floor(Math.random() * basuraImages.length)];
trash.style.backgroundImage = `url(${randomImage})`; // Set a random trash image
trash.style.left = `${Math.random() * (canvas.offsetWidth – 50)}px`; // Random X position
trash.style.top = `${Math.random() * (canvas.offsetHeight – 50)}px`; // Random Y position
// Event listener for dragging and throwing the trash
trash.addEventListener(‘mousedown’, (e) => startThrow(e, trash));
canvas.appendChild(trash); // Add the trash element to the canvas
}
// Generate the initial 5 trash items
for (let i = 0; i < 5; i++) {
createTrash();
}
// Function to handle the start of a throw
function startThrow(event, trash) {
const startX = event.clientX; // Initial mouse X position
const startY = event.clientY; // Initial mouse Y position
// Function to move the trash while dragging
function moveTrash(e) {
const dx = e.clientX – startX; // Change in X position
const dy = e.clientY – startY; // Change in Y position
trash.style.transform = `translate(${dx}px, ${dy}px)`; // Move the trash visually
}
// Function to finalize the throw
function endThrow(e) {
const dx = e.clientX – startX; // Total change in X
const dy = e.clientY – startY; // Total change in Y
const angle = Math.atan2(dy, dx); // Calculate angle of throw
const speed = Math.sqrt(dx * dx + dy * dy) / 10; // Calculate speed based on distance
launchTrash(trash, angle, speed); // Launch the trash with the calculated physics
document.removeEventListener(‘mousemove’, moveTrash); // Remove listeners
document.removeEventListener(‘mouseup’, endThrow);
}
// Add listeners for mouse movement and release
document.addEventListener(‘mousemove’, moveTrash);
document.addEventListener(‘mouseup’, endThrow);
}
// Function to launch the trash item with a trajectory
function launchTrash(trash, angle, speed) {
let x = parseInt(trash.style.left); // Initial X position
let y = parseInt(trash.style.top); // Initial Y position
const interval = setInterval(() => {
x += Math.cos(angle) * speed; // Update X position based on angle and speed
y += Math.sin(angle) * speed; // Update Y position based on angle and speed
trash.style.left = `${x}px`;
trash.style.top = `${y}px`;
// Check for collision with the bin
if (checkCollision(trash, cubo)) {
clearInterval(interval); // Stop movement
trash.remove(); // Remove the trash from the canvas
score++; // Increment score
scoreBoard.innerText = `Score: ${score}`; // Update the scoreboard
createTrash(); // Create a new trash item
}
// Remove trash if it leaves the canvas
if (x < 0 || y < 0 || x > canvas.offsetWidth || y > canvas.offsetHeight) {
clearInterval(interval); // Stop movement
trash.remove(); // Remove trash
createTrash(); // Create a new trash item
}
}, 20); // Update every 20ms
}
// Function to detect collisions between two elements
function checkCollision(obj1, obj2) {
const rect1 = obj1.getBoundingClientRect();
const rect2 = obj2.getBoundingClientRect();
return !(
rect1.right < rect2.left ||
rect1.left > rect2.right ||
rect1.bottom < rect2.top ||
rect1.top > rect2.bottom
);
}
// Timer functionality
function updateTimer() {
const minutes = Math.floor(timeLeft / 60); // Calculate minutes
const seconds = timeLeft % 60; // Calculate seconds
timerDisplay.innerText = `Time: ${minutes.toString().padStart(2, ‘0’)}:${seconds.toString().padStart(2, ‘0’)}`;
if (timeLeft > 0) {
timeLeft–; // Decrease time by 1 second
} else {
clearInterval(gameInterval); // Stop the timer
endGame(); // End the game
}
}
// Function to end the game
function endGame() {
alert(`Time’s up! Final Score: ${score}`);
}
// Start the game timer
gameInterval = setInterval(updateTimer, 1000);
This code demonstrates a simple yet engaging browser-based game with features like user interaction, collision detection, and real-time updates. The separation of logic into functions makes the code modular and easy to maintain. However, improvements like touch event support for mobile devices and enhanced physics could further refine the gameplay experience.
The game is an interactive browser-based application where players drag and throw trash items into a bin. The objective is to score as many points as possible within a time limit. The game mechanics include:
To replace the icons: