Untitled
<!DOCTYPE html> <html lang="sv"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Snake Game</title> <style> body { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #222; } canvas { border: 2px solid white; background-color: black; } </style> </head> <body> <canvas id="gameCanvas" width="400" height="400"></canvas> <script> const canvas = document.getElementById("gameCanvas"); const ctx = canvas.getContext("2d"); const gridSize = 20; let snake = [{ x: 200, y: 200 }]; let apple = { x: 100, y: 100 }; let dx = gridSize; let dy = 0; let gameRunning = true; function drawRect(color, x, y) { ctx.fillStyle = color; ctx.fillRect(x, y, gridSize, gridSize); } function drawSnake() { snake.forEach((segment, index) => { drawRect(index === 0 ? "lime" : "green", segment.x, segment.y); }); } function drawApple() { drawRect("red", apple.x, apple.y); } function moveSnake() { if (!gameRunning) return; const head = { x: snake[0].x + dx, y: snake[0].y + dy }; snake.unshift(head); if (head.x === apple.x && head.y === apple.y) { apple.x = Math.floor(Math.random() * (canvas.width / gridSize)) * gridSize; apple.y = Math.floor(Math.random() * (canvas.height / gridSize)) * gridSize; } else { snake.pop(); } if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height || checkCollision(head)) { gameRunning = false; alert("Game Over! Try again."); document.location.reload(); } } function checkCollision(head) { return snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y); } function changeDirection(event) { const key = event.key; if (key === "ArrowUp" && dy === 0) { dx = 0; dy = -gridSize; } else if (key === "ArrowDown" && dy === 0) { dx = 0; dy = gridSize; } else if (key === "ArrowLeft" && dx === 0) { dx = -gridSize; dy = 0; } else if (key === "ArrowRight" && dx === 0) { dx = gridSize; dy = 0; } } function gameLoop() { if (gameRunning) { ctx.clearRect(0, 0, canvas.width, canvas.height); moveSnake(); drawSnake(); drawApple(); } setTimeout(gameLoop, 100); } document.addEventListener("keydown", changeDirection); gameLoop(); </script> </body> </html>
Leave a Comment