Changed around line 1
+ const canvas = document.getElementById('gameCanvas');
+ const ctx = canvas.getContext('2d');
+ const scoreElement = document.getElementById('score');
+ const startBtn = document.getElementById('startBtn');
+
+ const gridSize = 20;
+ const tileCount = canvas.width / gridSize;
+
+ let snake = [{ x: 10, y: 10 }];
+ let direction = { x: 0, y: 0 };
+ let food = { x: 5, y: 5 };
+ let score = 0;
+ let gameLoop;
+
+ function drawGame() {
+ clearCanvas();
+ drawSnake();
+ drawFood();
+ moveSnake();
+ checkCollision();
+ }
+
+ function clearCanvas() {
+ ctx.fillStyle = '#000';
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ }
+
+ function drawSnake() {
+ ctx.fillStyle = '#4CAF50';
+ snake.forEach(segment => {
+ ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
+ });
+ }
+
+ function drawFood() {
+ ctx.fillStyle = '#FF5252';
+ ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
+ }
+
+ function moveSnake() {
+ const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
+ snake.unshift(head);
+ if (head.x === food.x && head.y === food.y) {
+ score++;
+ scoreElement.textContent = score;
+ placeFood();
+ } else {
+ snake.pop();
+ }
+ }
+
+ function placeFood() {
+ food.x = Math.floor(Math.random() * tileCount);
+ food.y = Math.floor(Math.random() * tileCount);
+ }
+
+ function checkCollision() {
+ const head = snake[0];
+ if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount || snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y)) {
+ clearInterval(gameLoop);
+ alert('Game Over! Your score: ' + score);
+ resetGame();
+ }
+ }
+
+ function resetGame() {
+ snake = [{ x: 10, y: 10 }];
+ direction = { x: 0, y: 0 };
+ score = 0;
+ scoreElement.textContent = score;
+ placeFood();
+ }
+
+ document.getElementById('upBtn').addEventListener('click', () => direction = { x: 0, y: -1 });
+ document.getElementById('leftBtn').addEventListener('click', () => direction = { x: -1, y: 0 });
+ document.getElementById('downBtn').addEventListener('click', () => direction = { x: 0, y: 1 });
+ document.getElementById('rightBtn').addEventListener('click', () => direction = { x: 1, y: 0 });
+
+ startBtn.addEventListener('click', () => {
+ resetGame();
+ gameLoop = setInterval(drawGame, 100);
+ });
+
+ document.addEventListener('keydown', (e) => {
+ switch (e.key) {
+ case 'ArrowUp': direction = { x: 0, y: -1 }; break;
+ case 'ArrowLeft': direction = { x: -1, y: 0 }; break;
+ case 'ArrowDown': direction = { x: 0, y: 1 }; break;
+ case 'ArrowRight': direction = { x: 1, y: 0 }; break;
+ }
+ });