Certainly! I'll enhance your Snake game by making the game board bigger and improving the gameplay experience significantly, all in a single HTML file as you requested.
All inline, minimal changes you can build on.
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>ULTRA CYBER-NEON SNAKE 2.0 - ENHANCED EDITION</title>
<link href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@700&display=swap" rel="stylesheet" />
<style>
/* --- Reset & Base --- */
*, *::before, *::after {
box-sizing: border-box;
margin: 0; padding: 0;
touch-action: manipulation;
}
html, body {
height: 100%;
overflow: hidden;
user-select: none;
background: linear-gradient(135deg, #0f2027, #0c1a20, #0d1520);
background-size: 600% 600%;
animation: bgShift 20s ease infinite;
font-family: 'Rajdhani', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: #0f9;
-webkit-tap-highlight-color: transparent;
}
@keyframes bgShift {
0%, 100% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
}
/* --- Neon Title --- */
.title {
font-size: 3.5rem;
text-transform: uppercase;
letter-spacing: 10px;
margin: 15px 0 20px;
text-align: center;
text-shadow:
0 0 5px #0f9,
0 0 10px #0f9,
0 0 20px #0f9,
0 0 40px #0ff,
0 0 80px #0ff;
animation: neonFlicker 3s infinite alternate;
position: relative;
font-weight: 900;
z-index: 10;
}
.title span {
color: #f0f;
animation: neonFlickerPink 3s infinite alternate;
text-shadow:
0 0 5px #f0f,
0 0 10px #f0f,
0 0 20px #f0f,
0 0 40px #ff00ff,
0 0 80px #ff00ff;
}
.subtitle {
font-size: 1.8rem;
color: #0ff;
text-shadow: 0 0 10px #0ff;
margin-bottom: 20px;
text-align: center;
animation: pulse 2s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 0.7; transform: scale(0.95); }
50% { opacity: 1; transform: scale(1); }
}
/* --- Game Container --- */
main.game-container {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
max-width: 120vmin;
position: relative;
padding: 10px;
user-select: none;
}
/* --- Game Frame --- */
#game {
position: relative;
width: 110vmin;
height: 110vmin;
background: #111;
border: 5px solid #0f9;
border-radius: 30px;
box-shadow:
inset 0 0 30px #0f9a,
0 0 40px rgba(0, 255, 200, 0.65);
touch-action: none;
overflow: hidden;
user-select: none;
}
canvas {
width: 100%;
height: 100%;
display: block;
background: transparent;
border-radius: 30px;
position: relative;
z-index: 2;
outline-offset: -5px;
outline: none;
}
/* --- Neon Glow --- */
.neon-glow {
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: radial-gradient(circle at center, rgba(0, 255, 200, 0.2), transparent 70%);
z-index: 1;
pointer-events: none;
animation: rotateGlow 40s linear infinite;
filter: blur(60px);
}
@keyframes rotateGlow {
100% { transform: rotate(360deg); }
}
/* --- Neon Flicker Animations --- */
@keyframes neonFlicker {
0%, 18%, 22%, 25%, 53%, 57%, 100% {
text-shadow:
0 0 6px #0f9,
0 0 12px #0f9,
0 0 24px #0f9,
0 0 48px #0ff,
0 0 96px #0ff;
}
20%, 24%, 55% {
text-shadow: none;
}
}
@keyframes neonFlickerPink {
0%, 18%, 22%, 25%, 53%, 57%, 100% {
text-shadow:
0 0 6px #f0f,
0 0 12px #f0f,
0 0 24px #f0f,
0 0 48px #f0f,
0 0 96px #f0f;
}
20%, 24%, 55% {
text-shadow: none;
}
}
/* --- Scoreboard --- */
#scoreboard {
margin-top: 15px;
text-align: center;
font-size: 1.8rem;
font-weight: 700;
animation: neonFlicker 3s infinite;
padding: 15px 30px;
border-radius: 20px;
background: rgba(0, 20, 30, 0.8);
box-shadow: 0 0 25px rgba(0, 255, 200, 0.6);
display: flex;
gap: 30px;
letter-spacing: 1px;
user-select: none;
align-items: center;
justify-content: center;
min-width: 420px;
}
#scoreboard.flash {
color: #fff;
text-shadow:
0 0 30px #0ff,
0 0 60px #0ff,
0 0 90px #0ff;
background: rgba(0, 40, 60, 0.95);
transform: scale(1.05);
transition: text-shadow 0.2s ease, color 0.2s ease, transform 0.3s ease, background 0.3s ease;
}
#scoreboard.combo {
animation: comboFlash 0.5s infinite alternate;
}
@keyframes comboFlash {
0% { background: rgba(200, 0, 100, 0.75); }
100% { background: rgba(255, 0, 150, 0.95); }
}
/* --- Controls --- */
#controls {
margin-top: 25px;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 18px;
width: 110vmin;
max-width: 450px;
position: relative;
z-index: 10;
user-select: none;
}
.btn {
background: linear-gradient(145deg, #0f9, #0c7);
border: none;
border-radius: 20px;
padding: 20px 0;
font-size: 1.7rem;
font-weight: 900;
box-shadow:
0 0 25px #0f9,
inset 0 0 10px rgba(255, 255, 255, 0.6);
cursor: pointer;
transition: all 0.25s ease;
user-select: none;
color: #000;
outline: none;
position: relative;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
/* Focus visible outline for accessibility */
.btn:focus-visible {
outline: 3px solid #0cffaa;
outline-offset: 3px;
}
.btn::before {
content: '';
position: absolute;
top: -60%;
left: -60%;
width: 220%;
height: 220%;
background: rgba(255, 255, 255, 0.22);
transform: rotate(45deg);
transition: transform 0.5s ease;
pointer-events: none;
}
.btn:hover,
.btn:focus-visible {
background: linear-gradient(145deg, #0cffaa, #0cffaa);
box-shadow:
0 0 50px #0cffaa,
inset 0 0 18px rgba(255, 255, 255, 0.9);
transform: scale(1.1);
z-index: 20;
}
.btn:hover::before {
transform: rotate(45deg) translate(120px, 120px);
}
.btn:active {
background: linear-gradient(145deg, #0c7, #0a5);
box-shadow:
inset 0 0 50px #0c7,
inset 0 0 20px rgba(0, 0, 0, 0.6);
transform: scale(0.95);
transition: none;
z-index: 15;
}
@media (max-width: 600px) {
.btn {
font-size: 1.5rem;
padding: 16px 0;
border-radius: 15px;
}
#scoreboard {
min-width: 320px;
font-size: 1.4rem;
padding: 12px 20px;
gap: 15px;
}
#controls {
max-width: 320px;
}
#game {
width: 95vmin;
height: 95vmin;
}
}
/* --- Restart Button --- */
#restartBtn, #soundToggleBtn, #pauseBtn {
margin-top: 20px;
background: linear-gradient(145deg, #0ff, #0cc);
color: #000;
border-radius: 20px;
padding: 18px 0;
font-size: 1.6rem;
font-weight: 700;
box-shadow:
0 0 38px #0ff,
inset 0 0 10px rgba(255, 255, 255, 0.7);
cursor: pointer;
user-select: none;
width: 110vmin;
max-width: 450px;
display: none;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
border: none;
text-transform: uppercase;
}
#restartBtn:focus-visible, #soundToggleBtn:focus-visible, #pauseBtn:focus-visible {
outline: 3px solid #0cc;
outline-offset: 3px;
}
#restartBtn::before, #soundToggleBtn::before, #pauseBtn::before {
content: '';
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: rgba(255, 255, 255, 0.2);
transform: rotate(45deg);
transition: transform 0.5s ease;
pointer-events: none;
}
#restartBtn:hover, #restartBtn:focus-visible,
#soundToggleBtn:hover, #soundToggleBtn:focus-visible,
#pauseBtn:hover, #pauseBtn:focus-visible {
background: linear-gradient(145deg, #0cc, #0aa);
box-shadow:
0 0 55px #0cc,
inset 0 0 18px rgba(255, 255, 255, 0.8);
transform: scale(1.05);
}
#restartBtn:hover::before, #soundToggleBtn:hover::before, #pauseBtn:hover::before {
transform: rotate(45deg) translate(130px, 130px);
}
#restartBtn:active, #soundToggleBtn:active, #pauseBtn:active {
background: linear-gradient(145deg, #099, #077);
box-shadow:
inset 0 0 45px #099,
inset 0 0 20px rgba(0, 0, 0, 0.7);
transform: scale(0.95);
transition: none;
}
/* --- Combo Meter --- */
#comboMeter {
width: 110vmin;
max-width: 450px;
height: 16px;
background: rgba(0, 20, 30, 0.8);
border-radius: 12px;
margin-top: 20px;
overflow: hidden;
position: relative;
box-shadow: 0 0 17px rgba(0, 255, 200, 0.5);
user-select: none;
}
#comboBar {
height: 100%;
width: 0%;
background: linear-gradient(90deg, #0f9, #f0f);
border-radius: 12px;
transition: width 0.3s ease;
box-shadow: 0 0 12px rgba(0, 255, 200, 0.9);
}
/* --- Power-ups --- */
.power-up {
position: absolute;
z-index: 3;
animation: float 3s infinite ease-in-out;
filter: drop-shadow(0 0 12px rgba(255, 255, 255, 0.95));
user-select: none;
}
@keyframes float {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-18px); }
}
/* --- Game Over Screen --- */
.game-over {
position: absolute;
top: 0; left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.95);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 200;
opacity: 0;
pointer-events: none;
transition: opacity 0.4s ease;
user-select: none;
}
.game-over.show {
opacity: 1;
pointer-events: all;
}
.game-over h2 {
font-size: 4.5rem;
color: #f0f;
text-shadow: 0 0 20px #f0f, 0 0 40px #f0f;
margin-bottom: 40px;
animation: neonFlickerPink 1.5s infinite alternate;
letter-spacing: 5px;
font-weight: 900;
}
.game-over p {
font-size: 2.2rem;
margin-bottom: 45px;
color: #0ff;
text-shadow: 0 0 14px #0ff;
letter-spacing: 2px;
user-select: all;
}
.game-over button.btn {
max-width: 320px;
width: 260px;
}
/* --- Snake Type Indicator --- */
#snakeType {
position: absolute;
top: 18px;
right: 18px;
font-size: 1.1rem;
background: rgba(0, 20, 30, 0.85);
padding: 10px 22px;
border-radius: 30px;
color: #0ff;
text-shadow: 0 0 10px #0ff;
z-index: 12;
box-shadow: 0 0 20px rgba(0, 255, 200, 0.5);
font-weight: 800;
letter-spacing: 1.5px;
user-select: none;
font-family: 'Rajdhani', sans-serif;
text-transform: uppercase;
user-select: none;
pointer-events: none;
}
/* --- Level Indicator --- */
#levelIndicator {
position: absolute;
top: 18px;
left: 18px;
font-size: 1.1rem;
background: rgba(0, 20, 30, 0.85);
padding: 10px 22px;
border-radius: 30px;
color: #0ff;
text-shadow: 0 0 10px #0ff;
z-index: 12;
box-shadow: 0 0 20px rgba(0, 255, 200, 0.5);
font-weight: 800;
letter-spacing: 1.5px;
user-select: none;
font-family: 'Rajdhani', sans-serif;
user-select: none;
pointer-events: none;
}
/* --- Cyber Grid --- */
.cyber-grid {
position: absolute;
top: 0; left: 0;
width: 100%;
height: 100%;
z-index: 0;
pointer-events: none;
opacity: 0.2;
background:
repeating-linear-gradient(
0deg,
transparent,
transparent 15px,
rgba(0, 255, 200, 0.12) 15px,
rgba(0, 255, 200, 0.12) 30px
),
repeating-linear-gradient(
90deg,
transparent,
transparent 15px,
rgba(0, 255, 200, 0.12) 15px,
rgba(0, 255, 200, 0.12) 30px
);
}
/* --- Power-up Timer --- */
.power-timer {
position: absolute;
bottom: 15px;
left: 50%;
transform: translateX(-50%);
width: 72%;
height: 14px;
background: rgba(0, 20, 30, 0.8);
border-radius: 7px;
overflow: hidden;
z-index: 12;
box-shadow: 0 0 15px rgba(0, 255, 200, 0.35);
display: none;
user-select: none;
user-select: none;
}
.power-timer-bar {
height: 100%;
width: 100%;
background: linear-gradient(90deg, #0f9, #f0f);
transition: width 0.1s linear;
border-radius: 7px;
}
/* --- Shield Effect --- */
.shield-effect {
position: absolute;
top: 50%;
left: 50%;
width: 110%;
height: 110%;
transform: translate(-50%, -50%);
border-radius: 50%;
border: 4px solid rgba(0, 200, 255, 0.55);
box-shadow: 0 0 40px rgba(0, 200, 255, 0.9);
animation: shieldPulse 2s infinite;
pointer-events: none;
z-index: 5;
filter: drop-shadow(0 0 12px #0ff);
}
@keyframes shieldPulse {
0%, 100% { transform: translate(-50%, -50%) scale(0.9); opacity: 0.5; }
50% { transform: translate(-50%, -50%) scale(1.1); opacity: 0.8; }
}
</style>
</head>
<body>
<div class="neon-glow"></div>
<div class="cyber-grid"></div>
<h1 class="title" aria-label="Game title: Ultra Cyber Snake 2.0">
ULTRA <span>CYBER</span> SNAKE 2.0
</h1>
<div class="subtitle" id="subtitle">SLOW EDITION - TWICE THE STRATEGY!</div>
<main class="game-container" role="main">
<section id="game" role="region" aria-label="Snake game area" tabindex="-1">
<canvas id="canvas" tabindex="0" aria-live="polite" aria-label="Game canvas"></canvas>
<div id="snakeType" aria-live="polite" aria-atomic="true">NORMAL</div>
<div id="levelIndicator">LEVEL: <span id="currentLevel">1</span></div>
<div class="power-timer" id="powerTimer" aria-hidden="true" title="Power-up time left">
<div class="power-timer-bar" id="powerTimerBar"></div>
</div>
<div class="game-over" id="gameOverScreen" role="dialog" aria-modal="true" aria-labelledby="gameOverTitle" tabindex="-1">
<h2 id="gameOverTitle">GAME OVER</h2>
<p>SCORE: <span id="finalScore">0</span></p>
<button id="restartBtn2" class="btn" type="button" aria-label="Restart game">PLAY AGAIN</button>
</div>
</section>
<div id="scoreboard" aria-live="polite" aria-atomic="true" role="status" aria-label="Scoreboard">
<div>SCORE: <span id="currentScore">0</span></div>
<div>HIGH: <span id="highScore">0</span></div>
</div>
<div id="comboMeter" aria-hidden="true" title="Combo meter">
<div id="comboBar"></div>
</div>
<nav 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>
</nav>
<button id="pauseBtn" type="button" aria-label="Pause or resume game">PAUSE GAME</button>
<button id="restartBtn" type="button" aria-label="Restart game">RESTART GAME</button>
<button id="soundToggleBtn" type="button" aria-label="Toggle sound effects">SOUND: ON</button>
<div class="mobile-notice" id="mobileNotice" aria-hidden="true" style="display:none;">Swipe or tap buttons to control the snake</div>
</main>
<!-- Audio elements aria-hidden -->
<audio id="eatSfx" preload="auto" aria-hidden="true" tabindex="-1"></audio>
<audio id="powerSfx" preload="auto" aria-hidden="true" tabindex="-1"></audio>
<audio id="gameOverSfx" preload="auto" aria-hidden="true" tabindex="-1"></audio>
<audio id="levelUpSfx" preload="auto" aria-hidden="true" tabindex="-1"></audio>
<script>
(() => {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
let audioContext;
let soundAllowed = true;
// Prepare audio context on user gesture for iOS etc.
function initAudioContext() {
if(!audioContext) {
audioContext = new AudioCtx();
}
}
// Play oscillator sound helper with ramp
function playOscillator({type='sine', frequencyStart, frequencyEnd, duration, gain=0.3}) {
if (!soundAllowed) return;
try {
if (!audioContext) initAudioContext();
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.type = type;
oscillator.frequency.setValueAtTime(frequencyStart, audioContext.currentTime);
if (frequencyEnd) {
oscillator.frequency.exponentialRampToValueAtTime(frequencyEnd, audioContext.currentTime + duration);
}
gainNode.gain.setValueAtTime(gain, audioContext.currentTime);
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.start();
gainNode.gain.exponentialRampToValueAtTime(0.00001, audioContext.currentTime + duration);
oscillator.stop(audioContext.currentTime + duration + 0.05);
oscillator.onended = () => {
oscillator.disconnect();
gainNode.disconnect();
};
} catch (e) {
// Fail silently
}
}
// Sounds
function generateEatSound() {
playOscillator({frequencyStart: 523.25, duration: 0.3}); // C5 note
}
function generatePowerSound() {
playOscillator({frequencyStart: 220, frequencyEnd: 880, duration: 0.5});
}
function generateGameOverSound() {
playOscillator({frequencyStart: 349.23, frequencyEnd: 130.81, duration: 0.7, gain: 0.4});
}
function generateLevelUpSound() {
playOscillator({frequencyStart: 523.25, frequencyEnd: 1046.5, duration: 0.5});
}
// DOM refs
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 scoreboard = document.getElementById('scoreboard');
const comboBar = document.getElementById('comboBar');
const snakeType = document.getElementById('snakeType');
const levelIndicator = document.getElementById('currentLevel');
const btns = document.querySelectorAll('.btn[data-dir]');
const restartBtn = document.getElementById('restartBtn');
const restartBtn2 = document.getElementById('restartBtn2');
const gameOverScreen = document.getElementById('gameOverScreen');
const finalScore = document.getElementById('finalScore');
const powerTimer = document.getElementById('powerTimer');
const powerTimerBar = document.getElementById('powerTimerBar');
const mobileNotice = document.getElementById('mobileNotice');
const pauseBtn = document.getElementById('pauseBtn');
const soundToggleBtn = document.getElementById('soundToggleBtn');
const subtitle = document.getElementById('subtitle');
// Updated config
const tileCount = 40; // Bigger board
let gridSize;
const baseFps = 10; // Slightly faster base than original slow 7.5
let currentFps = baseFps;
const maxApples = 6;
// Game state
let snake, velocity, nextVel, apples, score, gameOver;
let comboCounter, lastAppleTime, hue;
let effects;
let highScore = parseInt(localStorage.getItem('snakeHighScore'), 10) || 0;
let powerUps = [];
let snakeMode = 'normal';
let powerUpActive = false;
let powerUpEndTime = 0;
let level = 1;
let trailParticles = [];
let shieldHits = 0;
let laserShotsLeft = 0;
let laserCooldown = false;
let paused = false;
highEl.textContent = highScore;
levelIndicator.textContent = level;
// Show mobile notice if touch device
if ('ontouchstart' in window || navigator.maxTouchPoints > 0) {
mobileNotice.style.display = 'block';
mobileNotice.setAttribute('aria-hidden', 'false');
}
// Resize canvas and grid dynamically
function resizeCanvas() {
const size = Math.min(game.clientWidth, game.clientHeight);
canvas.width = size;
canvas.height = size;
gridSize = size / tileCount;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
/* HELPERS */
function colorGradient(isSnake) {
hue = (hue + 4) % 360;
if (isSnake) {
const c1 = `hsl(${hue},100%,60%)`;
const c2 = `hsl(${(hue + 45) % 360},100%,70%)`;
const grad = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
grad.addColorStop(0, c1);
grad.addColorStop(1, c2);
return grad;
} else {
const grad = ctx.createRadialGradient(0, 0, 5, 0, 0, gridSize * 0.6);
grad.addColorStop(0, `hsl(${hue},100%,80%)`);
grad.addColorStop(1, `hsl(${(hue + 70) % 360},80%,50%)`);
return grad;
}
}
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) &&
!powerUps.some(p => p.x === x && p.y === y);
}
// Spawn apples and power-ups
function spawnApples() {
while (apples.length < maxApples) {
const p = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount),
};
if (isEmpty(p.x, p.y)) apples.push(p);
}
if (Math.random() < 0.15 && !powerUpActive && powerUps.length === 0) {
const types = ['speed', 'ghost', 'shield', 'laser'];
const candidate = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount),
type: types[Math.floor(Math.random() * types.length)],
};
if (isEmpty(candidate.x, candidate.y)) powerUps.push(candidate);
}
}
// Effects
function addScoreFx(x, y, amt) {
effects.score.push({
x: x * gridSize + gridSize / 2,
y: y * gridSize + gridSize / 2,
alpha: 1,
text: '+' + amt,
size: 28,
});
}
function addParticles(x, y, color) {
for (let i = 0; i < 35; i++) {
effects.particles.push({
x: x * gridSize + gridSize / 2,
y: y * gridSize + gridSize / 2,
dx: (Math.random() - 0.5) * 12,
dy: (Math.random() - 0.5) * 12,
alpha: 1,
size: Math.random() * 7 + 3,
color: color || `hsla(${(hue + i * 20) % 360}, 100%, 70%, 1)`,
});
}
}
function updateEffects() {
for (let i = effects.score.length - 1; i >= 0; i--) {
const e = effects.score[i];
e.y -= 2;
e.alpha -= 0.025;
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;
if (p.alpha <= 0) effects.particles.splice(i, 1);
}
}
function flashScore() {
scoreboard.classList.add('flash');
setTimeout(() => scoreboard.classList.remove('flash'), 250);
generateEatSound();
}
function flashCombo() {
scoreboard.classList.add('combo');
setTimeout(() => scoreboard.classList.remove('combo'), 700);
}
// Trail particles for snake movement effect
function addTrailParticle(x, y) {
trailParticles.push({
x: x * gridSize + gridSize / 2,
y: y * gridSize + gridSize / 2,
size: gridSize * (0.7 + Math.random() * 0.3),
alpha: 0.7,
hue: (hue + Math.random() * 60) % 360,
life: 20,
});
}
function updateTrailParticles() {
for (let i = trailParticles.length - 1; i >= 0; i--) {
const p = trailParticles[i];
p.alpha -= 0.025;
p.size -= 0.22;
p.life--;
if (p.life <= 0 || p.alpha <= 0) trailParticles.splice(i, 1);
}
}
function drawTrailParticles() {
for (let p of trailParticles) {
ctx.globalAlpha = p.alpha;
ctx.fillStyle = `hsla(${p.hue}, 100%, 65%, ${p.alpha})`;
ctx.beginPath();
ctx.arc(p.x, p.y, p.size / 2, 0, Math.PI * 2);
ctx.fill();
}
ctx.globalAlpha = 1;
}
// Laser shot effect and logic
function shootLaser() {
if (laserShotsLeft <= 0 || laserCooldown) return;
laserShotsLeft--;
laserCooldown = true;
setTimeout(() => laserCooldown = false, 150); // Prevent super spam
const head = snake[0];
const targetX = (head.x + velocity.x + tileCount) % tileCount;
const targetY = (head.y + velocity.y + tileCount) % tileCount;
// Remove segment of snake in front (except head)
if (!['ghost', 'shield'].includes(snakeMode)) {
let choppedIndex = -1;
for (let i = 1; i < snake.length; i++) {
if (snake[i].x === targetX && snake[i].y === targetY) {
choppedIndex = i;
break;
}
}
if (choppedIndex > -1) {
// Remove those segments, snake shortens (does not die)
snake.splice(choppedIndex);
addParticles(targetX, targetY, 'rgba(255,85,0,1)');
}
}
// Visual laser line for short duration
laserVisuals.push({
fromX: head.x * gridSize + gridSize / 2,
fromY: head.y * gridSize + gridSize / 2,
toX: targetX * gridSize + gridSize / 2,
toY: targetY * gridSize + gridSize / 2,
alpha: 1,
life: 10,
});
try {
playOscillator({ type: 'square', frequencyStart: 1100, frequencyEnd: 880, duration: 0.2, gain: 0.3 });
} catch {}
}
let laserVisuals = [];
// Main game update loop
function update() {
if (gameOver || paused) return;
// Power-up timer
if (powerUpActive) {
const timeLeft = powerUpEndTime - Date.now();
if (timeLeft > 0) {
powerTimerBar.style.width = (timeLeft / 10000 * 100) + '%';
} else {
powerUpActive = false;
if (snakeMode === 'shield') shieldHits = 0;
if (snakeMode === 'laser') laserShotsLeft = 0;
snakeMode = 'normal';
snakeType.textContent = 'NORMAL';
snakeType.style.color = '#0ff';
powerTimer.style.display = 'none';
currentFps = baseFps;
subtitle.textContent = 'SLOW EDITION - TWICE THE STRATEGY!';
}
}
// Apply nextVel only if not reversing
if (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,
};
// Handle collisions
if (!['ghost', 'shield', 'laser'].includes(snakeMode) &&
snake.some((p, i) => i > 0 && p.x === head.x && p.y === head.y)) {
gameOver = true;
showGameOver();
return;
} else if (snakeMode === 'shield' && snake.some((p, i) => i > 0 && p.x === head.x && p.y === head.y)) {
// Shield absorbs one collision
shieldHits++;
if (shieldHits >= 2) {
// Shield broken for rest of power-up period
powerUpActive = false;
snakeMode = 'normal';
snakeType.textContent = 'NORMAL';
snakeType.style.color = '#0ff';
powerTimer.style.display = 'none';
currentFps = baseFps;
}
// Remove last snake segment instead of game over
snake.pop();
}
addTrailParticle(snake[0].x, snake[0].y);
snake.unshift(head);
let ateApple = false;
let collectedPower = false;
// Eat apples
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 < 2500) ? 6 : 0;
const comboBonus = comboCounter * 4;
const gain = 12 + timeBonus + comboBonus;
score += gain;
comboCounter++;
lastAppleTime = now;
comboBar.style.width = Math.min(100, comboCounter * 12) + '%';
if (comboCounter >= 3) flashCombo();
scoreEl.textContent = score;
// Level up every 70 points
const newLevel = Math.floor(score / 70) + 1;
if (newLevel > level) {
level = newLevel;
levelIndicator.textContent = level;
try { generateLevelUpSound(); } catch {}
// Increase speed by 8% per level
currentFps = baseFps * Math.min(3, 1 + (level - 1) * 0.08);
if (!powerUpActive) interval = 1000 / currentFps; // sync fps interval
subtitle.textContent = `LEVEL ${level} - ULTRA CYBER CHALLENGE!`;
}
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();
ateApple = true;
break;
}
}
// Collect power-ups
for (let i = 0; i < powerUps.length; i++) {
if (powerUps[i].x === head.x && powerUps[i].y === head.y) {
snakeMode = powerUps[i].type;
powerUpActive = true;
powerUpEndTime = Date.now() + 10000;
snakeType.textContent = snakeMode.toUpperCase();
const typeColors = {
speed: '#0f9',
ghost: '#f0f',
shield: '#0ff',
laser: '#ff5500',
};
snakeType.style.color = typeColors[snakeMode] || '#0ff';
powerTimer.style.display = 'block';
powerTimerBar.style.width = '100%';
// Reset shield & laser states
shieldHits = 0;
laserShotsLeft = 3;
subtitle.textContent = `POWER-UP: ${snakeMode.toUpperCase()} - ACTIVE!`;
if (snakeMode === 'speed') {
currentFps = baseFps * 2.2;
} else {
currentFps = baseFps * 1.1;
}
// Particles color based on power-up
let particleColor;
switch (snakeMode) {
case 'speed': particleColor = 'rgba(0,255,150,1)'; break;
case 'ghost': particleColor = 'rgba(255,0,200,1)'; break;
case 'shield': particleColor = 'rgba(0,200,255,1)'; break;
case 'laser': particleColor = 'rgba(255,85,0,1)'; break;
default: particleColor = null;
}
addParticles(head.x, head.y, particleColor);
generatePowerSound();
powerUps.splice(i, 1);
collectedPower = true;
break;
}
}
if (!ateApple && !collectedPower) {
comboCounter = 0;
comboBar.style.width = '0%';
snake.pop();
}
// Update trail
updateTrailParticles();
// Update laser visuals alpha and cleanup
laserVisuals.forEach(l => {
l.alpha -= 0.07;
l.life--;
});
laserVisuals = laserVisuals.filter(l => l.alpha > 0 && l.life > 0);
}
// Drawing function
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawTrailParticles();
// Draw grid background
ctx.strokeStyle = 'rgba(0, 200, 180, 0.12)';
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 power-ups
powerUps.forEach(p => {
const cx = p.x * gridSize + gridSize / 2;
const cy = p.y * gridSize + gridSize / 2;
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(Date.now() * 0.002);
ctx.shadowColor = p.type === 'speed' ? '#0f9' :
p.type === 'ghost' ? '#f0f' :
p.type === 'laser' ? '#ff5500' : '#0ff';
ctx.shadowBlur = 24;
if (p.type === 'speed') {
// Lightning bolt shape
ctx.fillStyle = '#0ff';
ctx.beginPath();
ctx.moveTo(0, -gridSize*0.32);
ctx.lineTo(gridSize*0.28, 0);
ctx.lineTo(0, gridSize*0.32);
ctx.lineTo(-gridSize*0.28, 0);
ctx.closePath();
ctx.fill();
} else if (p.type === 'ghost') {
// Ghost shape
ctx.fillStyle = '#f0f';
ctx.beginPath();
ctx.arc(0, 0, gridSize*0.32, 0, Math.PI);
ctx.lineTo(gridSize*0.32, gridSize*0.32);
ctx.quadraticCurveTo(gridSize*0.12, gridSize*0.52, 0, gridSize*0.32);
ctx.quadraticCurveTo(-gridSize*0.12, gridSize*0.52, -gridSize*0.32, gridSize*0.32);
ctx.closePath();
ctx.fill();
// Eyes
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc(-gridSize*0.12, -gridSize*0.11, gridSize*0.08, 0, Math.PI*2);
ctx.arc(gridSize*0.12, -gridSize*0.11, gridSize*0.08, 0, Math.PI*2);
ctx.fill();
} else if (p.type === 'laser') {
// Laser power-up
ctx.fillStyle = '#ff5500';
ctx.beginPath();
ctx.arc(0, 0, gridSize*0.32, 0, Math.PI*2);
ctx.fill();
ctx.strokeStyle = '#ff9900';
ctx.lineWidth = 4;
ctx.beginPath();
ctx.moveTo(-gridSize*0.28, 0);
ctx.lineTo(gridSize*0.28, 0);
ctx.moveTo(0, -gridSize*0.28);
ctx.lineTo(0, gridSize*0.28);
ctx.stroke();
} else {
// Shield shape
ctx.fillStyle = '#0ff';
ctx.beginPath();
ctx.arc(0, 0, gridSize*0.38, 0, Math.PI*2);
ctx.fill();
ctx.fillStyle = '#111';
ctx.beginPath();
ctx.arc(0, 0, gridSize*0.27, 0, Math.PI*2);
ctx.fill();
ctx.strokeStyle = '#0ff';
ctx.lineWidth = 4;
ctx.beginPath();
ctx.arc(0, 0, gridSize*0.34, 0, Math.PI*2);
ctx.stroke();
}
ctx.restore();
});
// Draw apples
apples.forEach(a => {
const cx = a.x * gridSize + gridSize / 2;
const cy = a.y * gridSize + gridSize / 2;
ctx.save();
ctx.translate(cx, cy);
const scale = 0.92 + 0.12 * Math.sin(Date.now() / 150);
ctx.scale(scale, scale);
ctx.shadowColor = '#f33';
ctx.shadowBlur = 20;
ctx.fillStyle = colorGradient(false);
ctx.beginPath();
ctx.ellipse(0, 0, gridSize*0.45, gridSize*0.6, Math.PI/6, 0, 2*Math.PI);
ctx.fill();
ctx.fillStyle = '#282';
ctx.beginPath();
ctx.ellipse(0, -gridSize*0.3, gridSize*0.18, gridSize*0.35, Math.PI/4, 0, 2*Math.PI);
ctx.fill();
ctx.restore();
});
// Draw snake
snake.forEach((s, i) => {
const px = s.x * gridSize, py = s.y * gridSize;
ctx.save();
// Opacity gradient from head to tail
let alpha = 1 - (i / snake.length) * 0.75;
alpha = Math.min(1, Math.max(0.15, alpha));
ctx.globalAlpha = alpha;
// Snake color per mode
if (snakeMode === 'speed') {
ctx.fillStyle = `hsl(${(hue + i * 12) % 360}, 100%, 62%)`;
} else if (snakeMode === 'ghost') {
ctx.fillStyle = `hsla(${(hue + 240 + i * 12) % 360}, 100%, 70%, ${alpha})`;
} else if (snakeMode === 'shield') {
ctx.fillStyle = `hsla(${(hue + 180 + i * 12) % 360}, 100%, 58%, ${alpha})`;
} else if (snakeMode === 'laser') {
ctx.fillStyle = `hsla(${(hue + 30 + i * 12) % 360}, 100%, 58%, ${alpha})`;
} else {
ctx.fillStyle = colorGradient(true);
}
ctx.shadowColor = snakeMode === 'ghost' ? '#f0f' :
snakeMode === 'laser' ? '#ff5500' : '#0ff';
ctx.shadowBlur = (i === 0 ? 30 : 20);
roundedRect(px + 3, py + 3, gridSize - 6, gridSize - 6, 10);
// Draw snake eyes on head
if (i === 0) {
const eyeSize = gridSize * 0.18;
ctx.fillStyle = '#000';
ctx.globalAlpha = 1;
// Eyes
ctx.beginPath();
ctx.arc(px + gridSize * 0.32, py + gridSize * 0.42, eyeSize, 0, Math.PI * 2);
ctx.arc(px + gridSize * 0.7, py + gridSize * 0.42, eyeSize, 0, Math.PI * 2);
ctx.fill();
// Pupils follow velocity direction
ctx.fillStyle = snakeMode === 'laser' ? '#ff5500' : '#fff';
const pupilOffsetX = velocity.x * eyeSize * 0.6;
const pupilOffsetY = velocity.y * eyeSize * 0.6;
ctx.beginPath();
ctx.arc(px + gridSize * 0.32 + pupilOffsetX, py + gridSize * 0.42 + pupilOffsetY, eyeSize * 0.55, 0, Math.PI * 2);
ctx.arc(px + gridSize * 0.7 + pupilOffsetX, py + gridSize * 0.42 + pupilOffsetY, eyeSize * 0.55, 0, Math.PI * 2);
ctx.fill();
// Laser eyes effect
if (snakeMode === 'laser') {
ctx.strokeStyle = '#ff5500';
ctx.lineWidth = 2.5;
ctx.beginPath();
ctx.moveTo(px + gridSize * 0.32 + pupilOffsetX * 4, py + gridSize * 0.42 + pupilOffsetY * 4);
ctx.lineTo(px + gridSize * 0.32 + pupilOffsetX * 10, py + gridSize * 0.42 + pupilOffsetY * 10);
ctx.moveTo(px + gridSize * 0.7 + pupilOffsetX * 4, py + gridSize * 0.42 + pupilOffsetY * 4);
ctx.lineTo(px + gridSize * 0.7 + pupilOffsetX * 10, py + gridSize * 0.42 + pupilOffsetY * 10);
ctx.stroke();
}
}
ctx.restore();
});
// Draw score particles & texts
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 = `bold ${e.size}px 'Rajdhani', 'Segoe UI', sans-serif`;
ctx.textAlign = 'center';
ctx.shadowColor = '#0f9';
ctx.shadowBlur = 14;
ctx.fillText(e.text, e.x, e.y);
});
// Shield halo on head
if (snakeMode === 'shield') {
const head = snake[0];
const cx = head.x * gridSize + gridSize / 2;
const cy = head.y * gridSize + gridSize / 2;
ctx.save();
ctx.beginPath();
ctx.arc(cx, cy, gridSize, 0, Math.PI * 2);
ctx.strokeStyle = 'rgba(0, 200, 255, 0.65)';
ctx.lineWidth = 5;
ctx.shadowColor = '#0ff';
ctx.shadowBlur = 30;
ctx.stroke();
ctx.restore();
}
// Laser visual beams
laserVisuals.forEach(l => {
ctx.save();
ctx.lineCap = 'round';
ctx.lineWidth = 6;
ctx.strokeStyle = `rgba(255,85,0,${l.alpha})`;
ctx.shadowColor = `rgba(255,150,50,${l.alpha})`;
ctx.shadowBlur = 25;
ctx.beginPath();
ctx.moveTo(l.fromX, l.fromY);
ctx.lineTo(l.toX, l.toY);
ctx.stroke();
ctx.restore();
});
}
// Input handling (touch & buttons & keyboard)
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) {
let dir;
if (Math.abs(dx) > Math.abs(dy)) {
dir = dx > 0 ? 'right' : 'left';
} else {
dir = dy > 0 ? 'down' : 'up';
}
changeDir(dir);
touchStart = null;
}
}, { passive: true });
canvas.addEventListener('touchend', () => { touchStart = null; });
btns.forEach(button => button.addEventListener('click', () => {
changeDir(button.dataset.dir);
canvas.focus();
}));
window.addEventListener('keydown', e => {
if(gameOver) return;
// Accept input only if canvas or controls in focus for arrow keys
const isInputFocused = (document.activeElement === canvas || game.contains(document.activeElement));
if(!isInputFocused && !gameOverScreen.classList.contains('show')) return;
const keyMap = {
ArrowUp: 'up', ArrowDown: 'down',
ArrowLeft: 'left', ArrowRight: 'right',
w: 'up', W: 'up',
s: 'down', S: 'down',
a: 'left', A: 'left',
d: 'right', D: 'right',
};
if(e.key === 'p' || e.key === 'P') {
e.preventDefault();
togglePause();
return;
}
if(e.key === ' ' && snakeMode === 'laser' && !paused) {
e.preventDefault();
shootLaser();
return;
}
const dir = keyMap[e.key];
if (dir) {
e.preventDefault();
changeDir(dir);
}
});
function changeDir(dir) {
const mapping = { up: { x: 0, y: -1 }, down: { x: 0, y: 1 }, left: { x: -1, y: 0 }, right: { x: 1, y: 0 } };
const newVel = mapping[dir];
if (newVel && (newVel.x !== -velocity.x || newVel.y !== -velocity.y)) {
nextVel = newVel;
}
}
// Show Game Over UI with focus trap and announce
function showGameOver() {
generateGameOverSound();
setTimeout(() => {
finalScore.textContent = score;
gameOverScreen.classList.add('show');
restartBtn.style.display = 'block';
pauseBtn.style.display = 'none';
soundToggleBtn.style.display = 'block';
restartBtn.focus();
canvas.setAttribute('aria-hidden', 'true');
subtitle.textContent = "GAME OVER - PRESS PLAY AGAIN";
}, 120);
}
// Hide Game Over UI
function hideGameOver() {
gameOverScreen.classList.remove('show');
restartBtn.style.display = 'none';
pauseBtn.style.display = 'block';
canvas.removeAttribute('aria-hidden');
subtitle.textContent = "SLOW EDITION - TWICE THE STRATEGY!";
}
// Init or reset game state
function initGame() {
snake = [];
for(let i = 0; i < 5; i++) {
snake.push({ x: Math.floor(tileCount/2) - i, y: Math.floor(tileCount/2) });
}
velocity = { x: 1, y: 0 };
nextVel = { x: 1, y: 0 };
apples = [];
powerUps = [];
score = 0;
comboCounter = 0;
lastAppleTime = 0;
hue = 0;
effects = { score: [], particles: [] };
gameOver = false;
snakeMode = 'normal';
powerUpActive = false;
powerUpEndTime = 0;
level = 1;
trailParticles = [];
shieldHits = 0;
laserShotsLeft = 0;
laserVisuals = [];
paused = false;
currentFps = baseFps;
interval = 1000 / currentFps;
comboBar.style.width = '0%';
snakeType.textContent = 'NORMAL';
snakeType.style.color = '#0ff';
scoreEl.textContent = score;
levelIndicator.textContent = level;
restartBtn.style.display = 'none';
powerTimer.style.display = 'none';
pauseBtn.style.display = 'block';
soundToggleBtn.style.display = 'block';
hideGameOver();
spawnApples();
canvas.focus();
}
// Pause toggle
function togglePause() {
paused = !paused;
if(paused) {
pauseBtn.textContent = "RESUME GAME";
subtitle.textContent = "PAUSED";
canvas.setAttribute('aria-busy', 'true');
} else {
pauseBtn.textContent = "PAUSE GAME";
subtitle.textContent = `LEVEL ${level} - ULTRA CYBER CHALLENGE!`;
canvas.removeAttribute('aria-busy');
}
}
// Restart buttons
restartBtn.addEventListener('click', () => {
initGame();
});
restartBtn2.addEventListener('click', () => {
initGame();
});
// Sound toggle button
soundToggleBtn.addEventListener('click', () => {
soundAllowed = !soundAllowed;
if (!audioContext && soundAllowed) {
initAudioContext();
}
soundToggleBtn.textContent = soundAllowed ? "SOUND: ON" : "SOUND: OFF";
});
// Main loop params
let lastTime = 0;
let delta = 0;
let interval = 1000 / currentFps;
// Main loop
function loop(ts = 0) {
if (!lastTime) lastTime = ts;
delta += ts - lastTime;
lastTime = ts;
interval = 1000 / currentFps;
while (delta >= interval) {
update();
updateEffects();
delta -= interval;
}
draw();
requestAnimationFrame(loop);
}
/* Initialize */
initGame();
requestAnimationFrame(loop);
})();
</script>
</body>
</html>
Open this file in Chrome, Firefox, Edge, Safari (modern versions) to test.