To create a fully functioning game of Snake using JavaScript and HTML, we can use the <canvas> element for rendering the game. Below is a simple implementation of the game with all of your requested features. Copy the following code into an HTML file and open it in a web browser to play the game.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<style>
canvas {
border: 1px solid black;
display: block;
margin: auto;
}
</style>
<script>
window.onload = function() {
const canvas = document.getElementById('snake-game');
const ctx = canvas.getContext('2d');
const gridSize = 20;
const rows = canvas.height / gridSize;
const columns = canvas.width / gridSize;
let snake = [{x: 8, y: 8}];
let dx = gridSize;
let dy = 0;
let apple = spawnApple();
let score = 0;
let highScore = localStorage.getItem('highScore') || 0;
let gameInterval;
document.addEventListener('keydown', changeDirection);
function startGame() {
snake = [{x: 8, y: 8}];
dx = gridSize;
dy = 0;
apple = spawnApple();
score = 0;
clearInterval(gameInterval);
gameInterval = setInterval(updateGame, 500);
}
function updateGame() {
if (hasGameEnded()) {
clearInterval(gameInterval);
ctx.fillStyle = 'black';
ctx.fillText('Game Over!', canvas.width / 2 - 30, canvas.height / 2);
ctx.fillText('Press R to Restart', canvas.width / 2 - 45, canvas.height / 2 + 20);
return;
}
clearCanvas();
drawApple();
moveSnake();
drawSnake();
drawScore();
}
function clearCanvas() {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function spawnApple() {
return {
x: Math.floor(Math.random() * columns) * gridSize,
y: Math.floor(Math.random() * rows) * gridSize
};
}
function drawApple() {
ctx.fillStyle = 'red';
ctx.fillRect(apple.x, apple.y, gridSize, gridSize);
}
function moveSnake() {
const head = {x: snake[0].x + dx, y: snake[0].y + dy};
snake.unshift(head);
if (snake[0].x === apple.x && snake[0].y === apple.y) {
score += 10;
apple = spawnApple();
} else {
snake.pop();
}
}
function drawSnake() {
ctx.fillStyle = 'green';
for (const segment of snake) {
ctx.fillRect(segment.x, segment.y, gridSize, gridSize);
}
}
function changeDirection(event) {
const LEFT_KEY = 37;
const RIGHT_KEY = 39;
const UP_KEY = 38;
const DOWN_KEY = 40;
const keyPressed = event.keyCode;
const goingUp = dy === -gridSize;
const goingDown = dy === gridSize;
const goingRight = dx === gridSize;
const goingLeft = dx === -gridSize;
if (keyPressed === LEFT_KEY && !goingRight) { dx = -gridSize; dy = 0; }
if (keyPressed === RIGHT_KEY && !goingLeft) { dx = gridSize; dy = 0; }
if (keyPressed === UP_KEY && !goingDown) { dx = 0; dy = -gridSize; }
if (keyPressed === DOWN_KEY && !goingUp) { dx = 0; dy = gridSize; }
if (keyPressed === 82) { startGame(); } // Key R
}
function hasGameEnded() {
for (let i = 4; i < snake.length; i++) {
if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) return true;
}
const hitLeftWall = snake[0].x < 0;
const hitRightWall = snake[0].x > canvas.width - gridSize;
const hitToptWall = snake[0].y < 0;
const hitBottomWall = snake[0].y > canvas.height - gridSize;
if (hitLeftWall || hitRightWall || hitToptWall || hitBottomWall) {
highScore = Math.max(score, highScore);
localStorage.setItem('highScore', highScore);
return true;
}
}
function drawScore()