Creating a fully-featured Snake Game that meets all the specified requirements involves integrating HTML, CSS, and JavaScript seamlessly. Below is a comprehensive implementation that covers the core functionalities along with several optional enhancements to enhance the gameplay experience.
Project Structure
- HTML (
index.html): Structures the layout with semantic elements, including the header, main game area, and footer.
- CSS (
styles.css): Styles the game with a modern aesthetic, implements light/dark modes, and ensures responsiveness.
- JavaScript (
script.js): Handles game logic, controls, animations, and optional features like leaderboard and sound effects.
1. HTML (index.html)
<!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>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Snake Game</h1>
<div class="controls">
<div class="score-container">
<span>Score: </span><span id="score">0</span>
</div>
<button id="start-btn">Start</button>
<label class="switch">
<input type="checkbox" id="mode-toggle">
<span class="slider"></span>
</label>
</div>
</header>
<main>
<canvas id="gameCanvas" width="400" height="400"></canvas>
</main>
<footer>
<div class="instructions">
<p>Use Arrow Keys to Move the Snake</p>
<button id="reset-btn">Reset Game</button>
</div>
<div class="leaderboard-container">
<h2>Leaderboard</h2>
<ol id="leaderboard">
<!-- Top scores will be appended here -->
</ol>
</div>
<div class="sound-control">
<label class="switch">
<input type="checkbox" id="sound-toggle" checked>
<span class="slider"></span>
</label>
<span>Sound</span>
</div>
</footer>
<script src="script.js"></script>
</body>
</html>
Explanation:
- Header: Contains the game title, score display, start button, and light/dark mode toggle.
- Main: Holds the
<canvas> element where the game is rendered.
- Footer: Provides game instructions, a reset button, leaderboard display, and sound control.
2. CSS (styles.css)
/* Root Variables for Light and Dark Modes */
:root {
--bg-color: #f0f0f0;
--canvas-bg: #ffffff;
--snake-color: #4caf50;
--food-color: #e91e63;
--header-footer-bg: #ffffff;
--text-color: #333333;
--button-bg: #4caf50;
--button-text: #ffffff;
--shadow: rgba(0, 0, 0, 0.2);
}
body.dark-mode {
--bg-color: #2c2c2c;
--canvas-bg: #3c3c3c;
--snake-color: #76ff03;
--food-color: #ff4081;
--header-footer-bg: #424242;
--text-color: #f0f0f0;
--button-bg: #76ff03;
--button-text: #333333;
--shadow: rgba(255, 255, 255, 0.2);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
display: flex;
flex-direction: column;
min-height: 100vh;
transition: background-color 0.5s, color 0.5s;
}
header, footer {
background-color: var(--header-footer-bg);
padding: 10px 20px;
box-shadow: 0 2px 4px var(--shadow);
display: flex;
align-items: center;
justify-content: space-between;
transition: background-color 0.5s;
}
h1 {
font-size: 24px;
}
.controls {
display: flex;
align-items: center;
gap: 15px;
}
.score-container {
font-size: 18px;
}
button {
padding: 8px 16px;
background-color: var(--button-bg);
color: var(--button-text);
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
opacity: 0.8;
}
main {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
canvas {
background-color: var(--canvas-bg);
border: 2px solid var(--text-color);
border-radius: 10px;
box-shadow: 0 4px 8px var(--shadow);
transition: background-color 0.5s, border 0.5s;
}
footer {
flex-direction: column;
gap: 10px;
}
.instructions {
display: flex;
align-items: center;
gap: 10px;
}
.leaderboard-container {
width: 100%;
max-width: 400px;
}
.leaderboard-container h2 {
margin-bottom: 5px;
}
#leaderboard {
list-style: decimal inside;
}
.sound-control {
display: flex;
align-items: center;
gap: 5px;
}
/* Toggle Switch Styles */
.switch {
position: relative;
display: inline-block;
width: 40px;
height: 20px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0; left: 0;
right: 0; bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 20px;
}
.slider:before {
position: absolute;
content: "";
height: 16px;
width: 16px;
left: 2px;
bottom: 2px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #4caf50;
}
input:checked + .slider:before {
transform: translateX(20px);
}
/* Responsive Design */
@media (max-width: 600px) {
h1 {
font-size: 20px;
}
.controls {
flex-direction: column;
gap: 10px;
}
canvas {
width: 90vw;
height: 90vw;
}
footer {
align-items: flex-start;
}
}
Explanation:
- CSS Variables: Defined for light and dark modes, enabling easy theme switching.
- Layout: Utilizes Flexbox for layout arrangements in header, main, and footer sections.
- Responsive Design: Media queries ensure the game adapts to various screen sizes.
- Toggle Switch: Custom styles for the light/dark mode and sound toggle switches.
- Transitions: Smooth transitions for theme switching and interactive elements.
3. JavaScript (script.js)
// Selecting DOM Elements
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreEl = document.getElementById('score');
const startBtn = document.getElementById('start-btn');
const resetBtn = document.getElementById('reset-btn');
const modeToggle = document.getElementById('mode-toggle');
const leaderboardEl = document.getElementById('leaderboard');
const soundToggle = document.getElementById('sound-toggle');
const CANVAS_SIZE = 400;
const GRID_SIZE = 20;
const INITIAL_SNAKE = [{x: 10, y:10}];
let snake = [...INITIAL_SNAKE];
let direction = {x: 0, y: 0};
let food = {x: 15, y: 15};
let score = 0;
let gameInterval = null;
let speed = 100;
let obstacles = [];
let isPaused = false;
let sounds = {
eat: new Audio('https://freesound.org/data/previews/341/341695_5260877-lq.mp3'),
gameOver: new Audio('https://freesound.org/data/previews/178/178180_3513878-lq.mp3')
};
// Ensure Food doesn't spawn on the snake or obstacles
function spawnFood() {
let newFood;
while(true){
newFood = {
x: Math.floor(Math.random() * GRID_SIZE),
y: Math.floor(Math.random() * GRID_SIZE)
};
if (!snake.some(segment => segment.x === newFood.x && segment.y === newFood.y) &&
!obstacles.some(obs => obs.x === newFood.x && obs.y === newFood.y)) {
break;
}
}
food = newFood;
}
// Initialize Obstacles (Optional Feature)
function initObstacles() {
obstacles = [];
const numObstacles = Math.floor(GRID_SIZE / 5);
for(let i=0; i<numObstacles; i++) {
let obs;
while(true){
obs = {
x: Math.floor(Math.random() * GRID_SIZE),
y: Math.floor(Math.random() * GRID_SIZE)
};
if (!snake.some(segment => segment.x === obs.x && segment.y === obs.y) &&
!(obs.x === food.x && obs.y === food.y)) {
break;
}
}
obstacles.push(obs);
}
}
// Update the leaderboard from localStorage
function updateLeaderboard(){
let leaderboard = JSON.parse(localStorage.getItem('leaderboard')) || [];
// Sort in descending order
leaderboard.sort((a, b) => b - a);
// Keep top 5
leaderboard = leaderboard.slice(0,5);
// Display
leaderboardEl.innerHTML = '';
leaderboard.forEach(score => {
const li = document.createElement('li');
li.textContent = score;
leaderboardEl.appendChild(li);
});
}
// Add current score to leaderboard
function addToLeaderboard(){
let leaderboard = JSON.parse(localStorage.getItem('leaderboard')) || [];
leaderboard.push(score);
localStorage.setItem('leaderboard', JSON.stringify(leaderboard));
updateLeaderboard();
}
// Draw everything on the canvas
function draw() {
// Clear Canvas
ctx.fillStyle = getComputedStyle(document.body).getPropertyValue('--canvas-bg');
ctx.fillRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
// Draw Obstacles
ctx.fillStyle = '#555555';
obstacles.forEach(obs => {
ctx.fillRect(obs.x * GRID_SIZE, obs.y * GRID_SIZE, GRID_SIZE, GRID_SIZE);
});
// Draw Food
ctx.fillStyle = getComputedStyle(document.body).getPropertyValue('--food-color');
ctx.beginPath();
ctx.arc(food.x * GRID_SIZE + GRID_SIZE/2, food.y * GRID_SIZE + GRID_SIZE/2, GRID_SIZE/2 - 2, 0, 2 * Math.PI);
ctx.fill();
// Bounce Animation
// For simplicity, static for now
// Draw Snake
ctx.fillStyle = getComputedStyle(document.body).getPropertyValue('--snake-color');
snake.forEach((segment, index) => {
ctx.fillRect(segment.x * GRID_SIZE, segment.y * GRID_SIZE, GRID_SIZE, GRID_SIZE);
// Add trailing effect for head
if(index === 0){
ctx.shadowColor = getComputedStyle(document.body).getPropertyValue('--snake-color');
ctx.shadowBlur = 10;
}
});
ctx.shadowBlur = 0;
}
// Move the snake
function moveSnake(){
const head = {x: snake[0].x + direction.x, y: snake[0].y + direction.y};
snake.unshift(head);
// Check if eaten food
if(head.x === food.x && head.y === food.y){
score++;
scoreEl.textContent = score;
if(soundToggle.checked) sounds.eat.play();
spawnFood();
// Optional: Increase speed
if(score % 5 === 0 && speed > 50){
clearInterval(gameInterval);
speed -= 10;
gameInterval = setInterval(gameLoop, speed);
}
} else {
snake.pop();
}
// Collision with walls
if(head.x < 0 || head.x >= GRID_SIZE || head.y < 0 || head.y >= GRID_SIZE){
endGame();
}
// Collision with self
for(let i=1; i<snake.length; i++){
if(head.x === snake[i].x && head.y === snake[i].y){
endGame();
}
}
// Collision with obstacles
for(let obs of obstacles){
if(head.x === obs.x && head.y === obs.y){
endGame();
}
}
}
// End the game
function endGame(){
clearInterval(gameInterval);
gameInterval = null;
if(soundToggle.checked) sounds.gameOver.play();
addToLeaderboard();
updateLeaderboard();
alert(`Game Over! Your score: ${score}`);
}
// Game Loop
function gameLoop(){
if(!isPaused){
moveSnake();
draw();
}
}
// Handle Key Presses
document.addEventListener('keydown', (e) => {
switch(e.key){
case 'ArrowUp':
if(direction.y === 0){
direction = {x: 0, y: -1};
}
break;
case 'ArrowDown':
if(direction.y === 0){
direction = {x: 0, y: 1};
}
break;
case 'ArrowLeft':
if(direction.x === 0){
direction = {x: -1, y: 0};
}
break;
case 'ArrowRight':
if(direction.x === 0){
direction = {x: 1, y: 0};
}
break;
case ' ':
togglePause();
break;
}
});
// Start or Restart the Game
function startGame(){
snake = [...INITIAL_SNAKE];
direction = {x: 0, y: 0};
score = 0;
scoreEl.textContent = score;
speed = 100;
spawnFood();
initObstacles();
if(gameInterval) clearInterval(gameInterval);
gameInterval = setInterval(gameLoop, speed);
}
// Reset the Game and Score
function resetGame(){
startGame();
// Optionally, clear leaderboard
// localStorage.removeItem('leaderboard');
}
// Toggle Light/Dark Mode
modeToggle.addEventListener('change', () => {
document.body.classList.toggle('dark-mode');
});
// Toggle Sound
soundToggle.addEventListener('change', () => {
// Muting handled by checking soundToggle.checked
});
// Start Button
startBtn.addEventListener('click', () => {
startGame();
});
// Reset Button
resetBtn.addEventListener('click', () => {
resetGame();
});
// Pause Functionality (Optional)
function togglePause(){
isPaused = !isPaused;
if(isPaused){
// Display paused message
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
ctx.fillStyle = '#ffffff';
ctx.font = '30px Arial';
ctx.textAlign = 'center';
ctx.fillText('Paused', CANVAS_SIZE/2, CANVAS_SIZE/2);
} else {
// Redraw
draw();
}
}
// Initialize Leaderboard on Load
updateLeaderboard();
// Responsive Canvas Size
function resizeCanvas(){
const containerWidth = Math.min(window.innerWidth, CANVAS_SIZE);
canvas.style.width = `${containerWidth}px`;
canvas.style.height = `${containerWidth}px`;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// Sound Availability Check
sounds.eat.addEventListener('error', () => {
// Handle if sound fails to load
});
sounds.gameOver.addEventListener('error', () => {
// Handle if sound fails to load
});
Explanation:
- Game Initialization: Sets up the initial state of the snake, food, score, and obstacles.
- Drawing Functions: Renders the snake, food, and obstacles on the canvas. Includes basic animations like shadow for the snake's head.
- Movement Logic: Updates the snake's position based on user input and checks for collisions.
- Collision Detection: Ends the game if the snake collides with walls, itself, or obstacles.
- Scoring System: Increments the score when food is eaten and updates the display. Also increases the snake's speed as the score increases to add difficulty.
- Leaderboard: Stores and displays the top scores using
localStorage.
- Sound Effects: Plays sounds for eating food and game over events, with a toggle to enable/disable sounds.
- Light/Dark Mode: Toggles the theme by adding/removing the
dark-mode class on the <body>.
- Pause Functionality: Allows pausing and resuming the game using the spacebar.
Assets
For sound effects, I've used URLs from freesound.org. You can replace these URLs with your own sound files or other sources as needed.
Running the Game
-
Directory Structure:
project-folder/
├── index.html
├── styles.css
└── script.js
-
Steps:
- Create a new folder (e.g.,
snake-game).
- Inside this folder, create three files:
index.html, styles.css, and script.js.
- Copy the respective code snippets provided above into these files.
- Open
index.html in your web browser.
Additional Enhancements
While the implementation covers many of the requested features, you can further enhance the game by:
- Particle Effects: Utilize canvas particle systems to create effects when the snake eats food or the game ends.
- Smooth Animations: Implement requestAnimationFrame for smoother game loops and animations.
- Advanced UI Elements: Add animations to buttons and other interactive elements for a more engaging user interface.
Feel free to customize and expand upon this foundation to create an even more engaging Snake Game!