body { margin: 0; overflow: hidden; /* Hide scrollbars */ background-color: #333; } canvas { display: block; /* Removes extra space below the canvas */ background-color: #000; } const canvas = document.getElementById('gameCanvas'); const ctx = document.getElementById('gameCanvas').getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; // Game state variables let gameOver = false; let score = 0; // Player object const player = { x: 50, y: 50, width: 30, height: 30, color: '#00FF00', // Green speed: 5, velocityX: 0, velocityY: 0, jumpStrength: 10, isJumping: true }; // Platform object const platform = { x: 0, y: canvas.height - 50, width: canvas.width, height: 50, color: '#555' // Dark gray }; // Keys pressed state const keys = {}; window.addEventListener('keydown', (e) => { keys[e.key] = true; }); window.addEventListener('keyup', (e) => { keys[e.key] = false; }); // Main game loop function gameLoop() { if (gameOver) return; update(); draw(); requestAnimationFrame(gameLoop); } // Update game state function update() { // Player horizontal movement player.velocityX = 0; if (keys['ArrowLeft']) { player.velocityX = -player.speed; } if (keys['ArrowRight']) { player.velocityX = player.speed; } // Player jump if (keys['ArrowUp'] && !player.isJumping) { player.velocityY = -player.jumpStrength * 2; player.isJumping = true; } // Apply gravity player.velocityY += 0.3; // Gravity pull // Update player position player.x += player.velocityX; player.y += player.velocityY; // Collision detection with platform if ( player.y + player.height > platform.y && player.x < platform.x + platform.width && player.x + player.width > platform.x ) { player.y = platform.y - player.height; player.isJumping = false; player.velocityY = 0; } // Boundary checks for the player if (player.x < 0) player.x = 0; if (player.x + player.width > canvas.width) player.x = canvas.width - player.width; // Game over condition (if player falls below the screen) if (player.y > canvas.height) { gameOver = true; alert('Game Over! Your score was: ' + score); } // Simple score increment (e.g., based on survival time) score++; } // Draw game objects function draw() { // Clear canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw player ctx.fillStyle = player.color; ctx.fillRect(player.x, player.y, player.width, player.height); // Draw platform ctx.fillStyle = platform.color; ctx.fillRect(platform.x, platform.y, platform.width, platform.height); // Draw score ctx.fillStyle = '#fff'; ctx.font = '24px Arial'; ctx.fillText(`Score: ${Math.floor(score / 60)}`, 10, 30); } // Start the game gameLoop();