Certainly! I've enhanced your Cyber-Neon Snake game with the following improvements—all contained in a single HTML file:
html
<!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 Enhanced</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;
outline: none;
box-sizing: content-box;
}
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;
text-shadow:
0 0 5px #0f9,
0 0 10px #0f9,
0 0 20px #0f9,
0 0 40px #0ff;
}
#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;
user-select: none;
}
.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;
color: #000;
outline-offset: 2px;
outline-color: transparent;
outline-style: solid;
user-select: 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, Restart, Mute Buttons */
#pauseBtn, #restartBtn, #muteBtn {
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-select: none;
}
#pauseBtn:hover, #pauseBtn:focus-visible,
#restartBtn:hover, #restartBtn:focus-visible,
#muteBtn:hover, #muteBtn:focus-visible {
background: #0cffaa;
box-shadow: 0 0 30px #0cffaa;
transform: scale(1.05);
}
#pauseBtn:active, #restartBtn:active, #muteBtn: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;
}
#muteBtn {
background: #999;
box-shadow: 0 0 15px #666 inset;
color: #222;
max-width: 120px;
margin: 8px auto 0;
font-weight: 600;
letter-spacing: 1px;
user-select: none;
}
#muteBtn.muted {
background: #333;
box-shadow: 0 0 15px #0f9 inset;
color: #0f9;
}
/* Overlays */
#overlay {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
background: rgba(0,0,0,0.7);
border-radius: 20px;
display: flex;
justify-content: center;
align-items: center;
color: #0f9;
font-weight: 700;
text-align: center;
flex-direction: column;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: 2.5rem;
pointer-events: none;
user-select: none;
z-index: 10;
opacity: 0;
transition: opacity 0.3s ease;
}
#overlay.visible {
pointer-events: auto;
opacity: 1;
}
#overlay p {
margin: 8px 0 0;
font-size: 1.4rem;
color: #0ff;
text-shadow:
0 0 10px #0ff,
0 0 40px #0ff,
0 0 80px #0ff;
}
/* Focus outline for accessibility */
#pauseBtn:focus-visible,
#restartBtn:focus-visible,
#muteBtn:focus-visible,
.btn:focus-visible {
outline: 3px solid #0cffaa;
outline-offset: 2px;
}
</style>
</head>
<body>
<div id="game" role="region" aria-label="Snake game area" tabindex="0">
<canvas id="canvas" tabindex="0" aria-live="polite" aria-label="Game canvas"></canvas>
<div id="overlay" role="alert" aria-live="assertive" aria-atomic="true"></div>
</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" aria-label="Scoreboard">
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>
<button id="muteBtn" type="button" aria-label="Toggle mute sound" title="Toggle mute sound">🔊</button>
<!-- Embedded sounds as base64 (simple beep for eat, and buzz for game over) -->
<audio id="eatSfx" preload="auto" aria-hidden="true">
<source src="data:audio/wav;base64,UklGRpQAAABXQVZFZm10IBAAAAABAAEAgLsAAAB3AgAEABAAZGF0YQAAAAA=" type="audio/wav" />
</audio>
<audio id="gameOverSfx" preload="auto" aria-hidden="true">
<source src="data:audio/wav;base64,UklGRlIAAABXQVZFZm10IBAAAAABAAEAgLsAAAB3AgAEABAAZGF0YQAAAAA=" type="audio/wav" />
</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');
const muteBtn = document.getElementById('muteBtn');
const overlay = document.getElementById('overlay');
// Configuration & State
const tileCount = 24;
let gridSize;
let fps = 10;
let speedIncrementStep = 5; // Increase speed every 5 apples eaten
let snake, velocity, nextVel, apples, score, gameOver, paused;
let comboCounter, lastAppleTime, hue;
let effects;
let highScore = Number(localStorage.getItem('snakeHighScore')) || 0;
let mute = false;
let speedIncrements = 0;
highEl.textContent = highScore;
// Special Golden Apple Chance [0-100%]
const goldenAppleChance = 0.15;
// Timing for Fixed FPS
let lastTime = 0;
let delta = 0;
let interval = 1000 / fps;
// 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: [] };
gameOver = false;
paused = false;
speedIncrements = 0;
fps = 10;
interval = 1000 / fps;
scoreEl.textContent = score;
restartBtn.style.display = 'none';
pauseBtn.textContent = 'Pause';
muteBtn.classList.toggle('muted', mute);
muteBtn.textContent = mute ? '🔈' : '🔊';
overlay.classList.remove('visible');
spawnApples();
game.focus();
}
// Resize Canvas
function resizeCanvas(){
const size = game.clientWidth;
canvas.width = size;
canvas.height = size;
gridSize = size / tileCount;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// Create color gradients for snake and apples
function colorGradient(isSnake){
if(isSnake){
const c1 = `hsl(${hue},100%,50%)`,
c2 = `hsl(${(hue+50)%360},90%,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.7);
g.addColorStop(0, `hsl(${hue},100%,75%)`);
g.addColorStop(1, `hsl(${(hue+60)%360},85%,35%)`);
return g;
}
}
// Rounded rectangle helper for neon blocks
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();
}
// Check if a tile is free (no snake or apple)
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 maintaining maxApples existing on field
const maxApples = 3;
function spawnApples(){
while(apples.length < maxApples){
const p = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount),
golden: false
};
// Assign golden apple on chance - only one special at a time
if(!apples.some(a => a.golden) && Math.random() < goldenAppleChance) {
p.golden = true;
}
if(isEmpty(p.x, p.y)) apples.push(p);
}
}
// Add floating score effects
function addScoreFx(x,y,amt, golden = false){
effects.score.push({
x: x*gridSize + gridSize/2,
y: y*gridSize + gridSize/2,
alpha: 1,
text: `+${amt}`,
size: 24,
color: golden ? '#FFD700' : '#00ff99'
});
}
// Add burst particles effect
function addParticles(x,y,color = `hsla(${(hue)%360},100%,60%,1)`){
for(let i=0;i<14;i++){
effects.particles.push({
x: x*gridSize + gridSize/2,
y: y*gridSize + gridSize/2,
dx: (Math.random()-0.5)*9,
dy: (Math.random()-0.5)*9,
alpha: 1,
size: Math.random()*4+2,
color
});
}
}
// Smoothly update & fade effects
function updateEffects(){
for(let i=effects.score.length-1; i>=0; i--){
const e = effects.score[i];
e.y -= 1.7;
e.alpha -= 0.02;
e.size += 0.3;
if(e.alpha <= 0) effects.score.splice(i,1);
}
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.035;
p.color = p.color.replace(/[\d\.]+\)$/g, p.alpha + ')'); // update alpha in hsla string
if(p.alpha <= 0) effects.particles.splice(i,1);
}
}
// Flash scoreboard on apple eaten
function flashScore(){
sb.classList.add('flash');
setTimeout(()=> sb.classList.remove('flash'), 200);
if(!mute) {
try {
eatSfx.currentTime = 0;
eatSfx.play();
} catch(e) {}
}
}
// Flash game over sound and overlay
function playGameOverSd(){
if(!mute) {
try {
gameOverSfx.currentTime = 0;
gameOverSfx.play();
} catch(e) {}
}
}
// Show overlay with message
function showOverlay(text, subtext = "") {
overlay.innerHTML = `<strong>${text}</strong>${subtext ? `<p>${subtext}</p>` : ""}`;
overlay.classList.add('visible');
}
function hideOverlay(){
overlay.classList.remove('visible');
}
// Update Game Logic (called at fixed FPS)
function update(){
// Accept turning only if not reversing
if((nextVel.x !== -velocity.x || nextVel.y !== -velocity.y)
&&(nextVel.x !== velocity.x || nextVel.y !== velocity.y)) {
velocity = nextVel;
}
// Calculate next head position with wrap-around
const head = {
x: (snake[0].x + velocity.x + tileCount) % tileCount,
y: (snake[0].y + velocity.y + tileCount) % tileCount
};
// Self collision -> game over
if(snake.some(p=>p.x===head.x && p.y===head.y)){
gameOver = true;
pauseBtn.disabled = true;
showGameOver();
return;
}
// Add new head
snake.unshift(head);
// Check if apple eaten
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();
// Bonus if eaten quickly
const timeBonus = (now - lastAppleTime < 3000) ? 5 : 0;
const comboBonus = comboCounter * 2;
let gain = 10 + timeBonus + comboBonus;
// Golden apple bonus and effect
if(apples[i].golden){
gain *= 3;
addParticles(head.x, head.y, '#FFD700');
flashScoreGolden();
} else {
addParticles(head.x, head.y);
flashScore();
}
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, apples[i].golden);
apples.splice(i,1);
spawnApples();
ate = true;
// Speed increase every speedIncrementStep apples eaten
if (comboCounter > 0 && comboCounter % speedIncrementStep === 0) {
speedIncrements++;
fps = Math.min(22, 10 + speedIncrements*2);
interval = 1000 / fps;
// Flash scoreboard to indicate speed up
sb.classList.add('flash');
setTimeout(()=> sb.classList.remove('flash'), 600);
}
break;
}
}
if(!ate){
comboCounter = 0;
snake.pop();
}
}
// Draw Game (called every frame)
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw 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);
ctx.moveTo(0, pos);
ctx.lineTo(canvas.width, pos);
ctx.stroke();
}
// Draw apples (normal and golden)
apples.forEach(a=>{
const cx = a.x*gridSize + gridSize/2;
const cy = a.y*gridSize + gridSize/2;
ctx.save();
ctx.translate(cx, cy);
if(a.golden){
// Golden apple glow
const gradient = ctx.createRadialGradient(0, 0, gridSize*0.1, 0, 0, gridSize*0.6);
gradient.addColorStop(0, '#FFD700');
gradient.addColorStop(1, 'rgba(255,215,0,0)');
ctx.fillStyle = gradient;
ctx.shadowColor = '#FFD700';
ctx.shadowBlur = 24;
ctx.beginPath();
ctx.arc(0, 0, gridSize*0.45, 0, 2*Math.PI);
ctx.fill();
// Golden core
ctx.fillStyle = '#FFEA00';
ctx.beginPath();
ctx.ellipse(0, 0, gridSize*0.35, gridSize*0.45, Math.PI/6, 0, 2*Math.PI);
ctx.fill();
// Leaf glow
ctx.fillStyle = '#A6A600';
ctx.beginPath();
ctx.ellipse(0, -gridSize*0.3, gridSize*0.15, gridSize*0.3, Math.PI/4, 0, 2*Math.PI);
ctx.fill();
} else {
// Normal apple neon
ctx.shadowColor = '#f44';
ctx.shadowBlur = 20;
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();
});
// Draw snake body and head with gradient glow
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 ? 26 : 18);
roundedRect(px+2, py+2, gridSize-4, gridSize-4, 10);
ctx.restore();
});
// Draw floating particles effect
effects.particles.forEach(p=>{
ctx.fillStyle = p.color;
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, 2*Math.PI);
ctx.fill();
});
// Draw score popups
effects.score.forEach(e=>{
ctx.fillStyle = e.color;
ctx.font = `${e.size}px Arial, sans-serif`;
ctx.textAlign = 'center';
ctx.shadowColor = e.color;
ctx.shadowBlur = 10;
ctx.fillText(e.text, e.x, e.y);
});
// Pause overlay
if(paused && !gameOver){
ctx.fillStyle = 'rgba(0,0,0,0.7)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#0f9';
ctx.font = 'bold 56px Segoe UI, Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.shadowColor = '#0ff';
ctx.shadowBlur = 20;
ctx.fillText('Paused', canvas.width / 2, canvas.height / 2);
}
// Game Over overlay
if(gameOver){
ctx.fillStyle = 'rgba(0,0,0,0.8)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#f33';
ctx.shadowColor = '#f00';
ctx.shadowBlur = 20;
ctx.font = 'bold 56px Segoe UI, Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('Game Over', canvas.width / 2, canvas.height / 2 - 52);
ctx.fillStyle = '#0f9';
ctx.shadowColor = '#0ff';
ctx.shadowBlur = 10;
ctx.font = 'bold 28px Segoe UI, Arial';
ctx.fillText(`Score: ${score}`, canvas.width / 2, canvas.height / 2 + 12);
ctx.font = '20px Segoe UI, Arial';
ctx.fillText('Press Restart to play again', canvas.width / 2, canvas.height / 2 + 52);
}
}
// Flash scoreboard for golden apple (special flash)
function flashScoreGolden(){
sb.classList.add('flash');
sb.style.color = '#FFD700';
setTimeout(()=>{
sb.classList.remove('flash');
sb.style.color = '#0f9';
}, 400);
if(!mute) {
try {
// Play special sound or just standard eat sound with volume change
eatSfx.currentTime = 0;
eatSfx.volume = 1;
eatSfx.play();
} catch(e) {}
}
}
// Input Handling - Keyboard, Buttons and Touch
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){
// Swipe direction priority: horizontal if greater delta, else vertical.
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.repeat) return; // prevent multiple rapid inputs
if(e.key === ' ') {
e.preventDefault();
if(!gameOver){
paused = !paused;
pauseBtn.textContent = paused ? 'Resume' : 'Pause';
if(paused) showOverlay('Paused');
else hideOverlay();
}
} 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];
// Prevent reversing direction
if(nv && (nv.x !== -velocity.x || nv.y !== -velocity.y)) nextVel = nv;
}
// Pause Button Handler
pauseBtn.addEventListener('click', () => {
if(gameOver) return;
paused = !paused;
pauseBtn.textContent = paused ? 'Resume' : 'Pause';
if(paused){
showOverlay('Paused');
} else {
hideOverlay();
game.focus();
}
});
// Restart Button Handler
restartBtn.addEventListener('click', () => {
initGame();
pauseBtn.disabled = false;
pauseBtn.focus();
});
// Mute Button Handler
muteBtn.addEventListener('click', () => {
mute = !mute;
muteBtn.classList.toggle('muted', mute);
muteBtn.textContent = mute ? '🔈' : '🔊';
// Pause all sounds if muted
if(mute){
eatSfx.pause();
gameOverSfx.pause();
}
});
// Show game over UI and play sound
function showGameOver(){
paused = true;
pauseBtn.textContent = 'Pause';
showOverlay('Game Over', `Score: ${score}\nPress Restart to play again`);
restartBtn.style.display = 'block';
restartBtn.focus();
playGameOverSd();
}
// Main game loop with fixed FPS and smooth animation
function loop(ts=0){
if(!lastTime) lastTime = ts;
delta += ts - lastTime;
lastTime = ts;
hue = (hue + 1.6) % 360; // Smooth color shift
updateEffects();
while(delta >= interval){
if(!paused && !gameOver) update();
delta -= interval;
}
draw();
requestAnimationFrame(loop);
}
// Initialize and start game
initGame();
requestAnimationFrame(loop);
})();
</script>
</body>
</html>
You can open this file directly in any modern browser (desktop or mobile) and play enhanced Cyber-Neon Snake.