<!DOCTYPE html>
<html>
<head>
<title>Snake</title>
<style>
#game-board {
width: 400px;
height: 400px;
background-color: #333;
position: relative;
}
.snake-block {
width: 20px;
height: 20px;
background-color: #fff;
position: absolute;
}
#food {
width: 20px;
height: 20px;
background-color: #f00;
position: absolute;
}
</style>
</head>
<body>
<h1>Snake</h1>
<div id="game-board"></div>
<script>
// Spielvariablen
var gameBoard = document.getElementById('game-board');
var blockSize = 20;
var widthInBlocks = gameBoard.offsetWidth / blockSize;
var heightInBlocks = gameBoard.offsetHeight / blockSize;
var score = 0;
// Snake
var snake = [
{x: widthInBlocks / 2, y: heightInBlocks / 2}
];
// Essen
var food = {
x: Math.floor(Math.random() * widthInBlocks),
y: Math.floor(Math.random() * heightInBlocks)
};
// Spiel starten
var gameLoop = setInterval(function() {
moveSnake();
drawSnake();
checkCollision();
}, 100);
// Schlange bewegen
function moveSnake() {
var head = {
x: snake[0].x + 1,
y: snake[0].y
};
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score++;
createFood();
} else {
snake.pop();
}
}
// Schlange zeichnen
function drawSnake() {
gameBoard.innerHTML = '';
snake.forEach(function(block) {
var snakeBlock = document.createElement('div');
snakeBlock.className = 'snake-block';
snakeBlock.style.left = block.x * blockSize + 'px';
snakeBlock.style.top = block.y * blockSize + 'px';
gameBoard.appendChild(snakeBlock);
});
var foodBlock = document.createElement('div');
foodBlock.id = 'food';
foodBlock.style.left = food.x * blockSize + 'px';
foodBlock.style.top = food.y * blockSize + 'px';
gameBoard.appendChild(foodBlock);
}
// Kollision überprüfen
function checkCollision() {
var head = snake[0];
// Kollision mit den Wänden
if (head.x < 0 || head.x === widthInBlocks || head.y < 0 || head.y === heightInBlocks) {
gameOver();
}
// Kollision mit dem Körper
for (var i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
gameOver();
}
}
}
// Spiel beenden
function gameOver() {
clearInterval(gameLoop);
alert('Game Over! Score: ' + score);
}
// Essen erstellen
function createFood() {
food = {
x: Math.floor(Math.random() * widthInBlocks),
y: Math.floor(Math.random() * heightInBlocks)
};
// Überprüfen, ob das Essen auf der Schlange generiert wurde
for (var i = 0; i < snake.length; i++) {
if (food.x === snake[i].x && food.y === snake[i].y) {
createFood();
break;
}
}
}
// Steuerung
document.addEventListener('keydown', function(event) {
var direction = event.keyCode;
// Pfeiltaste links
if (direction === 37 && snake[0].x !== snake[1].x + 1) {
snake[0].x -= 1;
}
// Pfeiltaste oben
else if (direction === 38 && snake[0].y !== snake[1].y + 1) {
snake[0].y -= 1;
}
// Pfeiltaste rechts
else if (direction === 39 && snake[0].x !== snake[1].x - 1) {
snake[0].x += 1;
}
// Pfeiltaste unten
else if (direction === 40 && snake[0].y !== snake[1].y - 1) {
snake[0].y += 1;
}
});
</script>
</body>
</html>