Okay, here is a visually enhanced, mobile-friendly classic Snake game packed into a single HTML file. You can copy and paste this code directly into an online HTML editor (like CodePen, JSFiddle, or even a simple text file saved as .html and opened in a browser).
Key Features:
Visually Appealing: Uses gradients, shadows, rounded corners, and a modern color scheme.
Mobile First: Designed with mobile touch controls (swipe gestures). Also works with keyboard arrow keys on desktops.
Responsive: Adapts reasonably well to different screen sizes.
Classic Gameplay: Eat food, grow longer, avoid walls and yourself.
Smooth Animation: Uses requestAnimationFrame for smoother rendering (though setInterval is used for game ticks for simpler speed control in this classic context).
Increasing Difficulty: Speed increases slightly as you score.
Clear UI: Score display, game over screen with restart.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Stunning Snake Game</title>
<style>
:root {
--bg-gradient-start: #1a2a3a;
--bg-gradient-end: #0f172a;
--snake-head-color: #4ade80; /* Bright Green */
--snake-body-color: #22c55e; /* Medium Green */
--food-color-start: #f87171; /* Light Red */
--food-color-end: #ef4444; /* Darker Red */
--text-color: #e2e8f0; /* Light Gray/Blue */
--border-color: #334155; /* Slate Gray */
--overlay-bg: rgba(15, 23, 42, 0.85); /* Semi-transparent Dark Blue */
--button-bg: #38bdf8; /* Light Blue */
--button-hover-bg: #0ea5e9; /* Darker Blue */
--shadow-color: rgba(0, 0, 0, 0.5);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html, body {
height: 100%;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
overscroll-behavior: none; /* Prevent pull-to-refresh/scroll on mobile */
touch-action: none; /* Prevent default touch actions like scrolling */
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: linear-gradient(135deg, var(--bg-gradient-start), var(--bg-gradient-end));
color: var(--text-color);
padding: 10px;
}
#game-container {
position: relative;
width: 95%;
max-width: 450px; /* Limit max width on larger screens */
aspect-ratio: 1 / 1; /* Make it square */
margin-bottom: 15px;
border-radius: 10px;
overflow: hidden; /* Clip shadows if needed */
box-shadow: 0 10px 25px var(--shadow-color);
}
#gameCanvas {
display: block;
width: 100%;
height: 100%;
background-color: var(--bg-gradient-end); /* Dark canvas background */
border: 2px solid var(--border-color);
border-radius: 8px; /* Match container slightly */
}
#ui-container {
text-align: center;
width: 95%;
max-width: 450px;
}
#score {
font-size: clamp(1.5rem, 5vw, 2rem); /* Responsive font size */
font-weight: bold;
margin-bottom: 15px;
text-shadow: 1px 1px 3px var(--shadow-color);
}
#gameOverScreen, #startScreen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: var(--overlay-bg);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
border-radius: 8px; /* Match canvas */
backdrop-filter: blur(5px);
z-index: 10;
transition: opacity 0.3s ease-in-out;
}
#gameOverScreen.hidden, #startScreen.hidden {
opacity: 0;
pointer-events: none;
}
#gameOverScreen h2, #startScreen h2 {
font-size: clamp(2rem, 8vw, 3rem);
margin-bottom: 10px;
text-shadow: 2px 2px 5px var(--shadow-color);
}
#gameOverScreen p, #startScreen p {
font-size: clamp(1.1rem, 4vw, 1.5rem);
margin-bottom: 25px;
}
.button {
padding: 12px 25px;
font-size: clamp(1rem, 4vw, 1.2rem);
font-weight: bold;
color: var(--bg-gradient-end);
background-color: var(--button-bg);
border: none;
border-radius: 50px; /* Pill shape */
cursor: pointer;
transition: background-color 0.2s ease, transform 0.1s ease;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}
.button:hover {
background-color: var(--button-hover-bg);
}
.button:active {
transform: scale(0.95);
}
#startScreen p {
font-size: clamp(0.9rem, 3vw, 1.1rem);
max-width: 80%;
}
/* Simple pulsing animation for food */
@keyframes pulse {
0% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.15); opacity: 0.85; }
100% { transform: scale(1); opacity: 1; }
}
.food-pulse {
/* Animation applied via JS drawing logic for canvas */
}
</style>
</head>
<body>
<div id="game-container">
<canvas id="gameCanvas"></canvas>
<div id="startScreen">
<h2>Snake Classic</h2>
<p>Use Arrow Keys or Swipe to control the snake.<br>Eat the red dots to grow!</p>
<button id="startButton" class="button">Start Game</button>
</div>
<div id="gameOverScreen" class="hidden">
<h2>Game Over!</h2>
<p id="finalScore">Your Score: 0</p>
<button id="restartButton" class="button">Restart Game</button>
</div>
</div>
<div id="ui-container">
<div id="score">Score: 0</div>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gameContainer = document.getElementById('game-container');
const scoreDisplay = document.getElementById('score');
const gameOverScreen = document.getElementById('gameOverScreen');
const startScreen = document.getElementById('startScreen');
const finalScoreDisplay = document.getElementById('finalScore');
const startButton = document.getElementById('startButton');
const restartButton = document.getElementById('restartButton');
// --- Game Configuration ---
const GRID_SIZE = 20; // Number of cells across/down
let canvasSize = 400; // Initial default, will resize
let TILE_SIZE = canvasSize / GRID_SIZE; // Size of each cell/snake segment
// --- Game State ---
let snake = [];
let dx = 0; // Direction x (1: right, -1: left, 0: none)
let dy = 0; // Direction y (1: down, -1: up, 0: none)
let food = { x: 0, y: 0 };
let score = 0;
let isGameOver = false;
let changingDirection = false; // Prevent multiple direction changes per tick
let gameSpeed = 150; // Milliseconds per tick (lower is faster)
let initialSpeed = 150;
let speedIncrement = 2; // Milliseconds to decrease per score point
let minSpeed = 60; // Fastest speed
let gameLoopTimeout;
let foodPulseState = 0; // For simple animation effect
let foodPulseSpeed = 0.05;
// --- Touch Controls ---
let touchStartX = 0;
let touchStartY = 0;
let touchEndX = 0;
let touchEndY = 0;
const MIN_SWIPE_DISTANCE = 30; // Minimum pixels for a swipe
// --- Initialization ---
function resizeCanvas() {
const containerWidth = gameContainer.clientWidth;
canvasSize = containerWidth; // Make canvas fill container width
canvas.width = canvasSize;
canvas.height = canvasSize;
TILE_SIZE = canvasSize / GRID_SIZE;
// Recalculate positions if game is running (optional, usually reset is better)
// For simplicity, we just ensure TILE_SIZE is updated for next reset/start
}
function initGame() {
snake = [
{ x: Math.floor(GRID_SIZE / 2), y: Math.floor(GRID_SIZE / 2) }, // Start in middle
{ x: Math.floor(GRID_SIZE / 2) - 1, y: Math.floor(GRID_SIZE / 2) },
{ x: Math.floor(GRID_SIZE / 2) - 2, y: Math.floor(GRID_SIZE / 2) },
];
dx = 1; // Start moving right
dy = 0;
score = 0;
gameSpeed = initialSpeed;
isGameOver = false;
changingDirection = false;
scoreDisplay.textContent = `Score: ${score}`;
gameOverScreen.classList.add('hidden');
startScreen.classList.add('hidden'); // Hide start screen once started
clearTimeout(gameLoopTimeout); // Clear any previous loops
placeFood();
gameLoop(); // Start the game loop
}
// --- Game Loop ---
function gameLoop() {
if (isGameOver) {
showGameOver();
return;
}
changingDirection = false; // Allow direction change for next tick
// Using setTimeout for variable speed control is simpler than requestAnimationFrame for classic snake
gameLoopTimeout = setTimeout(() => {
clearCanvas();
moveSnake();
drawGameElements();
gameLoop(); // Continue the loop
}, gameSpeed);
}
// --- Movement & Logic ---
function moveSnake() {
const head = { x: snake[0].x + dx, y: snake[0].y + dy };
// Check Wall Collision
if (head.x < 0 || head.x >= GRID_SIZE || head.y < 0 || head.y >= GRID_SIZE) {
isGameOver = true;
return;
}
// Check Self Collision
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
isGameOver = true;
return;
}
}
snake.unshift(head); // Add new head
// Check Food Collision
if (head.x === food.x && head.y === food.y) {
score++;
scoreDisplay.textContent = `Score: ${score}`;
placeFood();
// Increase speed (decrease interval), but not below minSpeed
gameSpeed = Math.max(minSpeed, initialSpeed - score * speedIncrement);
} else {
snake.pop(); // Remove tail if no food eaten
}
}
function placeFood() {
let newFoodPosition;
do {
newFoodPosition = {
x: Math.floor(Math.random() * GRID_SIZE),
y: Math.floor(Math.random() * GRID_SIZE)
};
} while (isFoodOnSnake(newFoodPosition)); // Ensure food isn't on the snake
food = newFoodPosition;
}
function isFoodOnSnake(position) {
for (const segment of snake) {
if (segment.x === position.x && segment.y === position.y) {
return true;
}
}
return false;
}
// --- Drawing ---
function clearCanvas() {
// Create a subtle gradient background for the canvas itself
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, getComputedStyle(document.documentElement).getPropertyValue('--bg-gradient-start'));
gradient.addColorStop(1, getComputedStyle(document.documentElement).getPropertyValue('--bg-gradient-end'));
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Optional: Draw grid lines (can be performance heavy)
/*
ctx.strokeStyle = 'rgba(51, 65, 85, 0.3)'; // --border-color with alpha
ctx.lineWidth = 0.5;
for (let i = 1; i < GRID_SIZE; i++) {
ctx.beginPath();
ctx.moveTo(i * TILE_SIZE, 0);
ctx.lineTo(i * TILE_SIZE, canvas.height);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, i * TILE_SIZE);
ctx.lineTo(canvas.width, i * TILE_SIZE);
ctx.stroke();
}
*/
}
function drawGameElements() {
drawSnake();
drawFood();
}
function drawRect(x, y, size, color, cornerRadius = 4, shadow = false) {
ctx.beginPath();
ctx.moveTo(x + cornerRadius, y);
ctx.lineTo(x + size - cornerRadius, y);
ctx.quadraticCurveTo(x + size, y, x + size, y + cornerRadius);
ctx.lineTo(x + size, y + size - cornerRadius);
ctx.quadraticCurveTo(x + size, y + size, x + size - cornerRadius, y + size);
ctx.lineTo(x + cornerRadius, y + size);
ctx.quadraticCurveTo(x, y + size, x, y + size - cornerRadius);
ctx.lineTo(x, y + cornerRadius);
ctx.quadraticCurveTo(x, y, x + cornerRadius, y);
ctx.closePath();
if (shadow) {
ctx.shadowColor = getComputedStyle(document.documentElement).getPropertyValue('--shadow-color');
ctx.shadowBlur = 8;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
}
ctx.fillStyle = color;
ctx.fill();
// Reset shadow for subsequent drawings
ctx.shadowColor = 'transparent';
ctx.shadowBlur = 0;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
}
function drawSnake() {
const headColor = getComputedStyle(document.documentElement).getPropertyValue('--snake-head-color');
const bodyColor = getComputedStyle(document.documentElement).getPropertyValue('--snake-body-color');
snake.forEach((segment, index) => {
const xPos = segment.x * TILE_SIZE;
const yPos = segment.y * TILE_SIZE;
const color = (index === 0) ? headColor : bodyColor;
// Add a subtle scaling effect to the head
const sizeMultiplier = (index === 0) ? 1.05 : 1.0;
const segmentSize = TILE_SIZE * 0.85 * sizeMultiplier; // Slightly smaller than tile for spacing
const offset = (TILE_SIZE - segmentSize) / 2;
drawRect(xPos + offset, yPos + offset, segmentSize, color, TILE_SIZE * 0.2, true); // Rounded corners based on tile size
});
}
function drawFood() {
const xPos = food.x * TILE_SIZE;
const yPos = food.y * TILE_SIZE;
// Pulsing effect calculation
foodPulseState += foodPulseSpeed;
if (foodPulseState > Math.PI * 2) {
foodPulseState -= Math.PI * 2;
}
const scale = 1 + Math.sin(foodPulseState) * 0.1; // Scale between 0.9 and 1.1
const foodSize = TILE_SIZE * 0.8 * scale; // Slightly smaller than tile
const offset = (TILE_SIZE - foodSize) / 2;
// Create gradient for food
const foodGradient = ctx.createRadialGradient(
xPos + TILE_SIZE / 2, yPos + TILE_SIZE / 2, foodSize * 0.1, // Inner circle
xPos + TILE_SIZE / 2, yPos + TILE_SIZE / 2, foodSize * 0.5 // Outer circle
);
foodGradient.addColorStop(0, getComputedStyle(document.documentElement).getPropertyValue('--food-color-start'));
foodGradient.addColorStop(1, getComputedStyle(document.documentElement).getPropertyValue('--food-color-end'));
drawRect(xPos + offset, yPos + offset, foodSize, foodGradient, TILE_SIZE * 0.5, true); // Make food circular
}
// --- Controls ---
function changeDirection(newDx, newDy) {
// Prevent changing direction if already changed this tick OR trying to reverse
if (changingDirection) return;
const goingUp = dy === -1;
const goingDown = dy === 1;
const goingLeft = dx === -1;
const goingRight = dx === 1;
// Prevent reversing direction
if (newDx === 1 && goingLeft) return;
if (newDx === -1 && goingRight) return;
if (newDy === 1 && goingUp) return;
if (newDy === -1 && goingDown) return;
dx = newDx;
dy = newDy;
changingDirection = true;
}
function handleKeyDown(event) {
// If game hasn't started (start screen visible), any key could potentially start it
if (startScreen.offsetParent !== null && !isGameOver) {
// You could add logic here to start on any key, but button is clearer
return;
}
// If game over screen is visible, Enter could restart
if (isGameOver && event.key === 'Enter') {
initGame();
return;
}
switch (event.key) {
case 'ArrowUp':
case 'w':
case 'W':
if (dy === 0) changeDirection(0, -1); // Prevent immediate reversal check
break;
case 'ArrowDown':
case 's':
case 'S':
if (dy === 0) changeDirection(0, 1);
break;
case 'ArrowLeft':
case 'a':
case 'A':
if (dx === 0) changeDirection(-1, 0);
break;
case 'ArrowRight':
case 'd':
case 'D':
if (dx === 0) changeDirection(1, 0);
break;
}
}
function handleTouchStart(event) {
touchStartX = event.changedTouches[0].screenX;
touchStartY = event.changedTouches[0].screenY;
}
function handleTouchEnd(event) {
touchEndX = event.changedTouches[0].screenX;
touchEndY = event.changedTouches[0].screenY;
handleSwipe();
}
function handleSwipe() {
const diffX = touchEndX - touchStartX;
const diffY = touchEndY - touchStartY;
const absDiffX = Math.abs(diffX);
const absDiffY = Math.abs(diffY);
// Check if it's a swipe (significant movement)
if (Math.max(absDiffX, absDiffY) < MIN_SWIPE_DISTANCE) {
return; // Not a significant swipe
}
// Determine dominant direction
if (absDiffX > absDiffY) {
// Horizontal swipe
if (diffX > 0 && dx === 0) { // Swiped right
changeDirection(1, 0);
} else if (diffX < 0 && dx === 0) { // Swiped left
changeDirection(-1, 0);
}
} else {
// Vertical swipe
if (diffY > 0 && dy === 0) { // Swiped down
changeDirection(0, 1);
} else if (diffY < 0 && dy === 0) { // Swiped up
changeDirection(0, -1);
}
}
}
// --- UI ---
function showGameOver() {
finalScoreDisplay.textContent = `Your Score: ${score}`;
gameOverScreen.classList.remove('hidden');
}
// --- Event Listeners ---
document.addEventListener('keydown', handleKeyDown);
canvas.addEventListener('touchstart', handleTouchStart, { passive: true }); // Use passive for performance if not preventing default scroll
canvas.addEventListener('touchend', handleTouchEnd, { passive: true });
// Need touch listeners on the container or body if user starts swipe outside canvas
gameContainer.addEventListener('touchstart', handleTouchStart, { passive: true });
gameContainer.addEventListener('touchend', handleTouchEnd, { passive: true });
startButton.addEventListener('click', initGame);
restartButton.addEventListener('click', initGame);
window.addEventListener('resize', resizeCanvas);
// --- Initial Setup ---
resizeCanvas(); // Set initial canvas size
// Game starts in the 'startScreen' state, waiting for button press.
</script>
</body>
</html>
How to Use:
Copy: Select all the code above.
Paste: Go to an online HTML editor like:
CodePen (Create a new Pen, paste into the HTML section)