Sure! Below is a complete Snake game built using HTML, CSS, and JavaScript. The game features:
- Beautiful graphics: Gradient backgrounds, rounded snake segments, and smooth animations.
- Growing snake: Each time the player eats an apple, the snake grows in length.
- Score display: The current score is displayed on the screen.
- Game Over screen: When the player loses, a Game Over message is shown, and the game can be restarted.
You can copy the code into a single HTML file and open it in your browser to play the game.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<style>
body {
background-color: #f0f0f0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
text-align: center;
margin: 0;
padding: 0;
}
h1 {
color: #333;
margin-top: 20px;
}
#gameCanvas {
background-color: #fff;
border: 2px solid #333;
margin: 20px auto;
display: block;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
</style>
</head>
<body>
<h1>Snake Game</h1>
<canvas id="gameCanvas" width="600" height="600"></canvas>
<script>
// Get the canvas and context
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
// Game settings
const gridSize = 20;
const tileCount = canvas.width / gridSize;
// Game variables
let snake = [{ x: tileCount / 2, y: tileCount / 2 }];
let velocity = { x: 0, y: 0 };
let apple = randomPosition();
let score = 0;
let gameOver = false;
// Game loop
function game() {
if (gameOver) {
drawGameOver();
return;
}
update();
draw();
}
function update() {
// Move snake
const head = { x: snake[0].x + velocity.x, y: snake[0].y + velocity.y };
// Check wall collision
if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
gameOver = true;
}
// Check self collision
for (const segment of snake) {
if (head.x === segment.x && head.y === segment.y) {
gameOver = true;
}
}
snake.unshift(head);
// Check apple collision
if (head.x === apple.x && head.y === apple.y) {
score++;
apple = randomPosition();
} else {
snake.pop();
}
}
function draw() {
// Draw background
ctx.fillStyle = "#fafafa";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw grid
drawGrid();
// Draw apple
drawApple();
// Draw snake
drawSnake();
// Draw score
ctx.fillStyle = "#333";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 10, 25);
}
function drawGameOver() {
ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#fff";
ctx.font = "50px Arial";
ctx.fillText("Game Over", canvas.width / 2 - 150, canvas.height / 2 - 25);
ctx.font = "20px Arial";
ctx.fillText("Press Space to Restart", canvas.width / 2 - 110, canvas.height / 2 + 25);
}
function drawGrid() {
ctx.strokeStyle = "#e0e0e0";
for (let i = 0; i <= tileCount; i++) {
ctx.beginPath();
ctx.moveTo(i * gridSize, 0);
ctx.lineTo(i * gridSize, canvas.height);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, i * gridSize);
ctx.lineTo(canvas.width, i * gridSize);
ctx.stroke();
}
}
function drawApple() {
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(apple.x * gridSize + gridSize / 2, apple.y * gridSize + gridSize / 2, gridSize / 2 - 2, 0, 2 * Math.PI);
ctx.fill();
}
function drawSnake() {
for (let i = 0; i < snake.length; i++) {
const part = snake[i];
const x = part.x * gridSize;
const y = part.y * gridSize;
// Create gradient
const gradient = ctx.createLinearGradient(x, y, x + gridSize, y + gridSize);
gradient.addColorStop(0, "#66bb6a");
gradient.addColorStop(1, "#388e3c");
ctx.fillStyle = gradient;
roundRect(ctx, x + 1, y + 1, gridSize - 2, gridSize - 2, 5);
ctx.fill();
}
}
// Draw rounded rectangle function
function roundRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.arcTo(x + width, y, x + width, y + height, radius);
ctx.arcTo(x + width, y + height, x, y + height, radius);
ctx.arcTo(x, y + height, x, y, radius);
ctx.arcTo(x, y, x + width, y, radius);
ctx.closePath();
}
// Handle keyboard input
document.addEventListener("keydown", function(e) {
if (e.keyCode === 37 && velocity.x !== 1) { // Left arrow
velocity = { x: -1, y: 0 };
} else if (e.keyCode === 38 && velocity.y !== 1) { // Up arrow
velocity = { x: 0, y: -1 };
} else if (e.keyCode === 39 && velocity.x !== -1) { // Right arrow
velocity = { x: 1, y: 0 };
} else if (e.keyCode === 40 && velocity.y !== -1) { // Down arrow
velocity = { x: 0, y: 1 };
} else if (e.keyCode === 32 && gameOver) { // Space bar to restart
resetGame();
}
});
// Reset game function
function resetGame() {
snake = [{ x: tileCount / 2, y: tileCount / 2 }];
velocity = { x: 0, y: 0 };
apple = randomPosition();
score = 0;
gameOver = false;
}
// Function to get random position for apple
function randomPosition() {
return {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};
}
// Start the game loop
setInterval(game, 100);
</script>
</body>
</html>
Instructions:
- Use the arrow keys to control the snake: Left, Up, Right, Down.
- Eat the red apples to grow the snake and increase your score.
- Avoid running into the walls or the snake's own body.
- When the game is over, press the Space bar to restart.
Features Explained:
- Canvas Drawing: The game uses the HTML5
<canvas> element for rendering graphics.
- Rounded Snake Segments: Custom function
roundRect is used to draw rounded rectangles for snake segments.
- Gradient Colors: Linear gradients are applied to the snake and background for a visually appealing look.
- Smooth Animations: The game updates every 100 milliseconds (10 frames per second) for smooth movement.
- Responsive Controls: Immediate response to keyboard inputs for controlling the snake.
Gameplay Screenshot:
[image: Snake Game Screenshot] open
(Note: Replace https://i.imgur.com/your-screenshot-url.png with an actual screenshot URL if you upload one.)
Enjoy playing the Snake game!