Imae
Lær navne

Lær navne

Snake Spil body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f0f0f0; } canvas { border: 1px solid #000; } const canvas = document.getElementById("gameCanvas"); const ctx = canvas.getContext("2d"); const gridSize = 20; const snake = [{ x: 9, y: 9 }]; let food = { x: 15, y: 15 }; let dx = 1; let dy = 0; let changingDirection = false; let gameRunning = false; function drawSnakePart(part) { ctx.fillStyle = "#00FF00"; ctx.fillRect(part.x * gridSize, part.y * gridSize, gridSize, gridSize); } function drawFood() { ctx.fillStyle = "#FF0000"; ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize); } function moveSnake() { const head = { x: snake[0].x + dx, y: snake[0].y + dy }; snake.unshift(head); if (head.x === food.x && head.y === food.y) { generateFood(); } else { snake.pop(); } } function generateFood() { const maxX = canvas.width / gridSize; const maxY = canvas.height / gridSize; food = { x: Math.floor(Math.random() * maxX), y: Math.floor(Math.random() * maxY) }; } function clearCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); } function checkCollision() { const head = snake[0]; if ( head.x = canvas.width / gridSize || head.y = canvas.height / gridSize ) { return true; } for (const part of snake.slice(1)) { if (part.x === head.x && part.y === head.y) { return true; } } return false; } function gameLoop() { if (checkCollision()) { alert("Game Over"); gameRunning = false; return; } changingDirection = false; clearCanvas(); drawFood(); snake.forEach(drawSnakePart); moveSnake(); if (gameRunning) { setTimeout(gameLoop, 100); } } document.getElementById("startButton").addEventListener("click", () => { if (!gameRunning) { gameRunning = true; generateFood(); gameLoop(); } }); document.addEventListener("keydown", (event) => { if (!gameRunning || changingDirection) return; const keyPressed = event.key; const up = dy === -1; const down = dy === 1; const left = dx === -1; const right = dx === 1; if (keyPressed === "ArrowUp" && !down) { dx = 0; dy = -1; changingDirection = true; } if (keyPressed === "ArrowDown" && !up) { dx = 0; dy = 1; changingDirection = true; } if (keyPressed === "ArrowLeft" && !right) { dx = -1; dy = 0; changingDirection = true; } if (keyPressed === "ArrowRight" && !left) { dx = 1; dy = 0; changingDirection = true; } });