<!DOCTYPE html>
<html>
<head>
<title>Simple Snake Game</title>
<style>
body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #222; }
canvas { border: 5px solid #fff; background: #000; }
</style>
</head>
<body>
<canvas id="game" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
let speed = 7;
let tileCount = 20;
let tileSize = canvas.width / tileCount - 2;
let headX = 10;
let headY = 10;
const snakeParts = [];
let tailLength = 2;
let appleX = 5;
let appleY = 5;
let xVelocity = 0;
let yVelocity = 0;
// Game Loop
function drawGame() {
changeSnakePosition();
let result = isGameOver();
if (result) return;
clearScreen();
checkAppleCollision();
drawApple();
drawSnake();
setTimeout(drawGame, 1000 / speed);
}
function isGameOver() {
if (yVelocity === 0 && xVelocity === 0) return false;
if (headX < 0 || headX === tileCount || headY < 0 || headY === tileCount) return true;
for (let i = 0; i < snakeParts.length; i++) {
if (headX === snakeParts[i].x && headY === snakeParts[i].y) return true;
}
return false;
}
function clearScreen() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawSnake() {
ctx.fillStyle = 'orange';
for (let i = 0; i < snakeParts.length; i++) {
let part = snakeParts[i];
ctx.fillRect(part.x * tileCount, part.y * tileCount, tileSize, tileSize);
}
snakeParts.push({x: headX, y: headY});
while (snakeParts.length > tailLength) { snakeParts.shift(); }
ctx.fillStyle = 'green';
ctx.fillRect(headX * tileCount, headY * tileCount, tileSize, tileSize);
}
function changeSnakePosition() {
headX = headX + xVelocity;
headY = headY + yVelocity;
}
function drawApple() {
ctx.fillStyle = "red";
ctx.fillRect(appleX * tileCount, appleY * tileCount, tileSize, tileSize);
}
function checkAppleCollision() {
if (appleX === headX && appleY === headY) {
appleX = Math.floor(Math.random() * tileCount);
appleY = Math.floor(Math.random() * tileCount);
tailLength++;
speed += 0.2;
}
}
document.body.addEventListener('keydown', keyDown);
function keyDown(event) {
if (event.keyCode == 38 && yVelocity != 1) { yVelocity = -1; xVelocity = 0; } // Up
if (event.keyCode == 40 && yVelocity != -1) { yVelocity = 1; xVelocity = 0; } // Down
if (event.keyCode == 37 && xVelocity != 1) { yVelocity = 0; xVelocity = -1; } // Left
if (event.keyCode == 39 && xVelocity != -1) { yVelocity = 0; xVelocity = 1; } // Right
}
drawGame();
</script>
</body>
</html>