html Copy code
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width,initial-scale=1,user-scalable=no,viewport-fit=cover"
/>
<title>Cyber-Neon Snake</title>
<style>
/* Reset & Base */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html, body {
height: 100%;
overflow: hidden;
user-select: none;
background: linear-gradient(45deg, #0f2027, #203a43, #2c5364);
background-size: 600% 600%;
animation: bgShift 20s ease infinite;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: #0f9;
}
@keyframes bgShift {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
/* Game Frame */
#game {
position: relative;
width: 90vmin;
height: 90vmin;
background: #111;
border: 4px solid #0f9;
border-radius: 20px;
box-shadow: inset 0 0 20px #0f9a;
touch-action: none;
user-select: none;
display: flex;
align-items: center;
justify-content: center;
}
canvas {
width: 100%;
height: 100%;
display: block;
background: #111;
border-radius: 20px;
image-rendering: pixelated;
}
/* Neon Scoreboard */
@keyframes neonFlicker {
0%, 18%, 22%, 25%, 53%, 57%, 100% {
text-shadow:
0 0 5px #0f9,
0 0 10px #0f9,
0 0 20px #0f9,
0 0 40px #0ff,
0 0 80px #0ff;
}
20%, 24%, 55% {
text-shadow: none;
}
}
#scoreboard {
margin-top: 12px;
text-align: center;
font-size: 1.5rem;
font-weight: 700;
animation: neonFlicker 3s infinite;
user-select: none;
min-width: 280px;
}
#scoreboard.flash {
color: #fff;
text-shadow:
0 0 25px #0ff,
0 0 50px #0ff,
0 0 75px #0ff;
transition: text-shadow 0.2s, color 0.2s;
}
/* Controls */
#controls {
margin-top: 12px;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
width: 90vmin;
max-width: 400px;
}
.btn {
background: #0f9;
border: none;
border-radius: 12px;
padding: 14px 0;
font-size: 1.4rem;
font-weight: 700;
box-shadow: 0 0 20px #0f9;
cursor: pointer;
transition: background 0.2s, box-shadow 0.2s, transform 0.1s;
user-select: none;
color: #000;
outline-offset: 2px;
outline-color: transparent;
outline-style: solid;
user-select: none;
user-drag: none;
-webkit-user-drag: none;
}
.btn:hover,
.btn:focus-visible {
background: #0cffaa;
box-shadow: 0 0 30px #0cffaa;
outline-color: #0cffaa;
transform: scale(1.05);
}
.btn:active {
background: #0c7;
box-shadow: inset 0 0 30px #0c7;
transform: scale(0.95);
}
@media (max-width: 400px) {
.btn {
font-size: 1.2rem;
padding: 10px 0;
}
}
/* Pause and Restart Buttons */
#pauseBtn, #restartBtn {
margin-top: 12px;
background: #0f9;
border: none;
border-radius: 12px;
padding: 12px 0;
font-size: 1.3rem;
font-weight: 700;
box-shadow: 0 0 20px #0f9;
cursor: pointer;
user-select: none;
width: 90vmin;
max-width: 400px;
transition: background 0.2s, box-shadow 0.2s, transform 0.1s;
color: #000;
user-drag: none;
-webkit-user-drag: none;
}
#pauseBtn:hover, #pauseBtn:focus-visible,
#restartBtn:hover, #restartBtn:focus-visible {
background: #0cffaa;
box-shadow: 0 0 30px #0cffaa;
transform: scale(1.05);
}
#pauseBtn:active, #restartBtn:active {
background: #0c7;
box-shadow: inset 0 0 30px #0c7;
transform: scale(0.95);
}
#restartBtn {
background: #0ff;
box-shadow: 0 0 25px #0ff;
display: none;
}
#restartBtn:hover, #restartBtn:focus-visible {
background: #0cc;
box-shadow: 0 0 40px #0cc;
}
#restartBtn:active {
background: #099;
box-shadow: inset 0 0 30px #099;
}
</style>
</head>
<body>
<div id="game" role="region" aria-label="Snake game area">
<canvas id="canvas" tabindex="0" aria-live="polite" aria-label="Game canvas"></canvas>
</div>
<div id="controls" aria-label="Directional controls">
<button class="btn" data-dir="left" aria-label="Move left" type="button">←</button>
<button class="btn" data-dir="up" aria-label="Move up" type="button">↑</button>
<button class="btn" data-dir="down" aria-label="Move down" type="button">↓</button>
<button class="btn" data-dir="right" aria-label="Move right" type="button">→</button>
</div>
<div id="scoreboard" aria-live="polite" aria-atomic="true" role="status">
Score: <span id="currentScore">0</span> | High: <span id="highScore">0</span>
</div>
<button id="pauseBtn" type="button" aria-label="Pause game">Pause</button>
<button id="restartBtn" type="button" aria-label="Restart game">Restart Game</button>
<audio id="eatSfx" preload="auto" aria-hidden="true" src="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YQAAAAA="></audio>
<audio id="gameOverSfx" preload="auto" aria-hidden="true" src="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YQAAAAA="></audio>
<script>
(function(){
// DOM & Audio References
const game = document.getElementById('game');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const scoreEl = document.getElementById('currentScore');
const highEl = document.getElementById('highScore');
const sb = document.getElementById('scoreboard');
const eatSfx = document.getElementById('eatSfx');
const gameOverSfx= document.getElementById('gameOverSfx');
const btns = document.querySelectorAll('.btn');
const pauseBtn = document.getElementById('pauseBtn');
const restartBtn = document.getElementById('restartBtn');
// Configuration & State
const tileCount = 24;
let gridSize;
const baseFps = 10;
let fps = baseFps;
const maxApples = 3;
let snake, velocity, nextVel, apples, score, gameOver, paused;
let comboCounter, lastAppleTime, hue;
let effects;
let highScore = parseInt(localStorage.getItem('snakeHighScore'),10) || 0;
highEl.textContent = highScore;
// Timing for Fixed FPS
let lastTime = 0;
let delta = 0;
let interval = 1000 / fps;
// Device Pixel Ratio for crisp canvas
function resizeCanvas(){
const size = game.clientWidth;
const dpr = window.devicePixelRatio || 1;
canvas.width = size * dpr;
canvas.height = size * dpr;
canvas.style.width = size + 'px';
canvas.style.height = size + 'px';
ctx.setTransform(1,0,0,1,0,0); // reset transform
ctx.scale(dpr, dpr);
gridSize = size / tileCount;
}
resizeCanvas();
window.addEventListener('resize', () => {
resizeCanvas();
});
// Initialize Game
function initGame() {
snake = [
{x:12,y:12},
{x:11,y:12},
{x:10,y:12}
];
velocity = {x:1, y:0};
nextVel = {x:1, y:0};
apples = [];
score = 0;
comboCounter = 0;
lastAppleTime = 0;
hue = 0;
effects = { score: [], particles: [], trail: [] };
gameOver = false;
paused = false;
fps = baseFps;
interval = 1000 / fps;
scoreEl.textContent = score;
restartBtn.style.display = 'none';
pauseBtn.textContent = 'Pause';
spawnApples();
clearTrail();
}
// Clear trail effects
function clearTrail() {
effects.trail = [];
}
// Helper Functions
function colorGradient(isSnake){
if(isSnake){
const c1 = `hsl(${hue},100%,50%)`,
c2 = `hsl(${(hue+40)%360},100%,60%)`,
g = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
g.addColorStop(0, c1);
g.addColorStop(1, c2);
return g;
} else {
const g = ctx.createRadialGradient(0,0,5, 0,0, gridSize*0.6);
g.addColorStop(0, `hsl(${hue},100%,70%)`);
g.addColorStop(1, `hsl(${(hue+60)%360},80%,40%)`);
return g;
}
}
function roundedRect(x,y,w,h,r){
ctx.beginPath();
ctx.moveTo(x+r,y); ctx.lineTo(x+w-r,y);
ctx.quadraticCurveTo(x+w,y, x+w,y+r);
ctx.lineTo(x+w,y+h-r);
ctx.quadraticCurveTo(x+w,y+h, x+w-r,y+h);
ctx.lineTo(x+r,y+h);
ctx.quadraticCurveTo(x,y+h, x,y+h-r);
ctx.lineTo(x,y+r);
ctx.quadraticCurveTo(x,y, x+r,y);
ctx.closePath();
ctx.fill();
}
function isEmpty(x,y){
return !snake.some(s=>s.x===x&&s.y===y) && !apples.some(a=>a.x===x&&a.y===y);
}
// Spawn Apples avoiding snake and near head
function spawnApples(){
while(apples.length < maxApples){
const p = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};
// Avoid snake and apples
if(isEmpty(p.x, p.y) && distance(p, snake[0]) > 4) apples.push(p);
}
}
function distance(p1, p2){
const dx = Math.min(Math.abs(p1.x - p2.x), tileCount - Math.abs(p1.x - p2.x));
const dy = Math.min(Math.abs(p1.y - p2.y), tileCount - Math.abs(p1.y - p2.y));
return Math.sqrt(dx*dx + dy*dy);
}
// Effects
function addScoreFx(x,y,amt){
effects.score.push({
x: x*gridSize + gridSize/2,
y: y*gridSize + gridSize/2,
alpha: 1, text: '+'+amt, size: 24
});
}
function addParticles(x,y){
for(let i=0;i<12;i++){
effects.particles.push({
x: x*gridSize + gridSize/2,
y: y*gridSize + gridSize/2,
dx: (Math.random()-0.5)*8,
dy: (Math.random()-0.5)*8,
alpha: 1, size: Math.random()*4+2
});
}
}
function updateEffects(){
// Score floating texts
for(let i=effects.score.length-1; i>=0; i--){
const e = effects.score[i];
e.y -= 1.5;
e.alpha -= 0.02;
e.size += 0.3;
if(e.alpha <= 0) effects.score.splice(i,1);
}
// Particles
for(let i=effects.particles.length-1; i>=0; i--){
const p = effects.particles[i];
p.x += p.dx;
p.y += p.dy;
p.alpha -= 0.03;
p.color = `hsla(${(hue + i*30)%360},100%,60%,${p.alpha})`;
if(p.alpha <= 0) effects.particles.splice(i,1);
}
// Trail effect (snake body glow)
const trailMax = 10;
if(!gameOver && !paused){
effects.trail.push({ ...snake[0], alpha: 0.3 });
if(effects.trail.length > trailMax) effects.trail.shift();
}
// Fade trail alphas
for(let i=effects.trail.length-1; i>=0; i--){
effects.trail[i].alpha -= 0.03;
if(effects.trail[i].alpha <= 0) effects.trail.splice(i,1);
}
}
function flashScore(){
sb.classList.add('flash');
setTimeout(()=> sb.classList.remove('flash'), 200);
try {
eatSfx.currentTime = 0;
eatSfx.play();
} catch(e) {}
}
function playGameOverSound(){
try {
gameOverSfx.currentTime = 0;
gameOverSfx.play();
} catch(e) {}
}
// Update Game Logic
function update(){
// Update velocity if nextVel is valid (no 180° turns)
if((nextVel.x !== -velocity.x || nextVel.y !== -velocity.y)
&&(nextVel.x !== velocity.x || nextVel.y !== velocity.y)) {
velocity = nextVel;
}
const head = {
x: (snake[0].x + velocity.x + tileCount) % tileCount,
y: (snake[0].y + velocity.y + tileCount) % tileCount
};
// Check collision with self
if(snake.some(p=>p.x===head.x && p.y===head.y)){
gameOver = true;
showGameOver();
playGameOverSound();
return;
}
snake.unshift(head);
let ate = false;
for(let i=0; i<apples.length; i++){
if(apples[i].x===head.x && apples[i].y===head.y){
const now = Date.now();
const timeBonus = (now - lastAppleTime < 3000) ? 5 : 0;
const comboBonus = comboCounter * 2;
const gain = 10 + timeBonus + comboBonus;
score += gain;
comboCounter++;
lastAppleTime = now;
scoreEl.textContent = score;
if(score > highScore){
highScore = score;
localStorage.setItem('snakeHighScore', highScore);
highEl.textContent = highScore;
}
addScoreFx(head.x, head.y, gain);
addParticles(head.x, head.y);
flashScore();
apples.splice(i,1);
spawnApples();
ate = true;
// Increase speed every 50 points (max 25 fps)
if(score % 50 === 0 && fps < 25){
fps += 1;
interval = 1000 / fps;
}
break;
}
}
if(!ate){
comboCounter = 0;
snake.pop();
}
}
// Draw Game
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Grid
ctx.strokeStyle = '#222';
ctx.lineWidth = 1;
for(let i=0; i<=tileCount; i++){
const pos = i * gridSize;
ctx.beginPath();
ctx.moveTo(pos, 0);
ctx.lineTo(pos, canvas.height / (window.devicePixelRatio || 1));
ctx.moveTo(0, pos);
ctx.lineTo(canvas.width / (window.devicePixelRatio || 1), pos);
ctx.stroke();
}
// Trail glow behind snake
effects.trail.forEach((t,i) => {
const px = t.x*gridSize, py = t.y*gridSize;
ctx.save();
ctx.fillStyle = `rgba(0,255,255,${t.alpha * 0.3})`;
ctx.shadowColor = `rgba(0,255,255,${t.alpha * 0.7})`;
ctx.shadowBlur = 15;
roundedRect(px+4, py+4, gridSize-8, gridSize-8, 6);
ctx.restore();
});
// Apples
apples.forEach(a=>{
const cx = a.x*gridSize + gridSize/2;
const cy = a.y*gridSize + gridSize/2;
ctx.save();
ctx.translate(cx, cy);
ctx.shadowColor = '#f44';
ctx.shadowBlur = 18;
ctx.fillStyle = colorGradient(false);
ctx.beginPath();
ctx.ellipse(0,0, gridSize*0.4, gridSize*0.55, Math.PI/6, 0, 2*Math.PI);
ctx.fill();
ctx.fillStyle = '#282';
ctx.beginPath();
ctx.ellipse(0, -gridSize*0.3, gridSize*0.15, gridSize*0.3, Math.PI/4, 0, 2*Math.PI);
ctx.fill();
ctx.restore();
});
// Snake
snake.forEach((s,i)=>{
const px = s.x*gridSize, py = s.y*gridSize;
ctx.save();
ctx.fillStyle = colorGradient(true);
ctx.shadowColor = '#0ff';
ctx.shadowBlur = (i===0 ? 30 : 20);
roundedRect(px+2, py+2, gridSize-4, gridSize-4, 8);
ctx.restore();
});
// Effects
effects.particles.forEach(p=>{
ctx.fillStyle = p.color;
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, 2*Math.PI);
ctx.fill();
});
effects.score.forEach(e=>{
ctx.fillStyle = `rgba(0,255,150,${e.alpha})`;
ctx.font = `${e.size}px Arial`;
ctx.textAlign = 'center';
ctx.shadowColor = '#0f9';
ctx.shadowBlur = 10;
ctx.fillText(e.text, e.x, e.y);
});
// Paused Overlay
if (paused) {
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#0f9';
ctx.font = '48px Arial';
ctx.textAlign = 'center';
ctx.fillText('Paused', canvas.width / 2, canvas.height / 2);
}
// Game Over Overlay
if (gameOver) {
ctx.fillStyle = 'rgba(0,0,0,0.7)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#f00';
ctx.font = '48px Arial';
ctx.textAlign = 'center';
ctx.fillText('Game Over', canvas.width / 2, canvas.height / 2 - 40);
ctx.fillStyle = '#0f9';
ctx.font = '24px Arial';
ctx.fillText(`Score: ${score}`, canvas.width / 2, canvas.height / 2 + 20);
ctx.fillText('Press Restart to play again', canvas.width / 2, canvas.height / 2 + 60);
}
}
// Input Handling
let touchStart = null;
const minSwipe = 30;
canvas.addEventListener('touchstart', e=>{
if(e.touches.length === 1) {
touchStart = { x: e.touches[0].clientX, y: e.touches[0].clientY };
}
}, { passive: true });
canvas.addEventListener('touchmove', e=>{
if(!touchStart) return;
const dx = e.touches[0].clientX - touchStart.x;
const dy = e.touches[0].clientY - touchStart.y;
if(Math.abs(dx) > minSwipe || Math.abs(dy) > minSwipe){
const dir = Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? 'right' : 'left') : (dy > 0 ? 'down' : 'up');
changeDir(dir);
touchStart = null;
}
}, { passive: true });
canvas.addEventListener('touchend', () => { touchStart = null; });
btns.forEach(b => b.addEventListener('click', () => changeDir(b.dataset.dir)));
window.addEventListener('keydown', e => {
if (e.key === ' ') {
e.preventDefault();
if (!gameOver) {
togglePause();
}
} else {
const keyMap = {
ArrowUp: 'up',
ArrowDown: 'down',
ArrowLeft: 'left',
ArrowRight: 'right',
w: 'up',
s: 'down',
a: 'left',
d: 'right',
W: 'up',
S: 'down',
A: 'left',
D: 'right'
};
const dir = keyMap[e.key];
if (dir) {
e.preventDefault();
changeDir(dir);
}
}
});
function changeDir(dir){
const map = { up:{x:0,y:-1}, down:{x:0,y:1}, left:{x:-1,y:0}, right:{x:1,y:0} };
const nv = map[dir];
if(nv && (nv.x !== -velocity.x || nv.y !== -velocity.y)) nextVel = nv;
}
// Pause and Game Over
function togglePause(){
if (!gameOver) {
paused = !paused;
pauseBtn.textContent = paused ? 'Resume' : 'Pause';
}
}
pauseBtn.addEventListener('click', togglePause);
function showGameOver(){
gameOver = true;
restartBtn.style.display = 'block';
restartBtn.focus();
}
restartBtn.addEventListener('click', () => {
initGame();
});
// Main Loop
function loop(ts=0){
if(!lastTime) lastTime = ts;
delta += ts - lastTime;
lastTime = ts;
hue = (hue + 2) % 360; // Smooth color shift
updateEffects();
while(delta >= interval){
if (!paused && !gameOver) {
update();
}
delta -= interval;
}
draw();
requestAnimationFrame(loop);
}
// Start Game
initGame();
requestAnimationFrame(loop);
})();
</script>
</body>
</html>
Feel free to replace the base64 audio data with your own sound files encoded as base64 for eat and game over sounds. If you want me to embed actual sounds, just ask!