
snake
.htmlSnake Game body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f4f4f4; } canvas { border: 2px solid #000; } const canvas = document.getElementById("gameCanvas"); const ctx = canvas.getContext("2d"); const box = 20; let snake = [{ x: 9 * box, y: 10 * box }]; let food = { x: Math.floor(Math.random() * 19 + 1) * box, y: Math.floor(Math.random() * 19 + 1) * box, }; let score = 0; let direction; let game = setInterval(draw, 200); document.addEventListener("keydown", directionControl); function directionControl(event) { if (event.key === "ArrowLeft" && direction !== "RIGHT") direction = "LEFT"; else if (event.key === "ArrowUp" && direction !== "DOWN") direction = "UP"; else if (event.key === "ArrowRight" && direction !== "LEFT") direction = "RIGHT"; else if (event.key === "ArrowDown" && direction !== "UP") direction = "DOWN"; } function collision(newHead, array) { for (let i = 0; i < array.length; i++) { if (newHead.x === array[i].x && newHead.y === array[i].y) { return true; } } return false; } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw snake for (let i = 0; i < snake.length; i++) { ctx.fillStyle = i === 0 ? "green" : "lightgreen"; ctx.fillRect(snake[i].x, snake[i].y, box, box); ctx.strokeStyle = "white"; ctx.strokeRect(snake[i].x, snake[i].y, box, box); } // Draw food ctx.fillStyle = "red"; ctx.fillRect(food.x, food.y, box, box); // Old head position let snakeX = snake[0].x; let snakeY = snake[0].y; // Direction if (direction === "LEFT") snakeX -= box; if (direction === "UP") snakeY -= box; if (direction === "RIGHT") snakeX += box; if (direction === "DOWN") snakeY += box; // Snake eats food if (snakeX === food.x && snakeY === food.y) { score++; food = { x: Math.floor(Math.random() * 19 + 1) * box, y: Math.floor(Math.random() * 19 + 1) * box, }; } else { snake.pop(); } // New head position let newHead = { x: snakeX, y: snakeY }; // Game over conditions if ( snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collision(newHead, snake) ) { clearInterval(game); alert("Game Over! Your score is " + score); } snake.unshift(newHead); // Display score ctx.fillStyle = "black"; ctx.font = "20px Arial"; ctx.fillText("Score: " + score, 10, 20); }