/** * This function initializes the game and starts the gameplay loop */ function startGame() { // Initialize game variables and objects let score = 0; let player = { x: 0, y: 0, speed: 5 }; let obstacles = []; // Start the gameplay loop setInterval(() => { // Move the player player.x += player.speed; // Generate new obstacles if (Math.random() < 0.1) { obstacles.push({ x: 800, y: Math.random() * 400, width: 50, height: 50 }); } // Move the obstacles obstacles.forEach(obstacle => { obstacle.x -= player.speed; }); // Check for collisions obstacles.forEach(obstacle => { if ( player.x < obstacle.x + obstacle.width && player.x + 50 > obstacle.x && player.y < obstacle.y + obstacle.height && player.y + 50 > obstacle.y ) { // Game over alert("Game over!"); score = 0; player.x = 0; player.y = 0; obstacles = []; } }); // Update the score score += player.speed; // Render the game renderGame(score, player, obstacles); }, 1000 / 60); } /** * This function renders the game on the screen * * @param {number} score The player's current score * @param {object} player The player object containing x, y, and speed properties * @param {array} obstacles An array of obstacle objects containing x, y, width, and height properties */ function renderGame(score, player, obstacles) { // Clear the screen ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw the player ctx.fillStyle = "red"; ctx.fillRect(player.x, player.y, 50, 50); // Draw the obstacles ctx.fillStyle = "green"; obstacles.forEach(obstacle => { ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height); }); // Draw the score ctx.fillStyle = "black"; ctx.font = "30px Arial"; ctx.fillText(`Score: ${score}`, 10, 50); } // Get the canvas and context elements const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Start the game startGame();