gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
Improve: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta…
- User
Improve:
code - Assistant
Improve:
/* 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, 0 0 30px rgba(0, 255, 153, 0.2);
touch-action: none;
user-select: none;
outline: none;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
display: block;
background: #111;
border-radius: 20px;
}
/* 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;
display: flex;
justify-content: center;
gap: 20px;
flex-wrap: wrap;
}
#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;
}
.score-container {
display: flex;
flex-direction: column;
align-items: center;
min-width: 120px;
background: rgba(0, 20, 15, 0.7);
padding: 8px 16px;
border-radius: 12px;
border: 1px solid #0f9;
box-shadow: 0 0 10px rgba(0, 255, 153, 0.3);
}
.score-label {
font-size: 0.9rem;
opacity: 0.8;
margin-bottom: 4px;
}
/* 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;
}
.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;
}
}
/* Top Control Bar */
#top-controls {
display: flex;
justify-content: space-between;
width: 90vmin;
max-width: 400px;
margin-bottom: 12px;
gap: 12px;
}
#top-controls .btn {
flex: 1;
padding: 10px 0;
font-size: 1.1rem;
}
#difficulty {
background: #0f9;
color: #000;
border: none;
border-radius: 12px;
padding: 0 15px;
font-size: 1.1rem;
font-weight: 700;
box-shadow: 0 0 20px #0f9;
cursor: pointer;
outline: none;
text-align: center;
}
#difficulty option {
background: #111;
color: #0f9;
}
/* Game Over Modal */
#gameOverModal {
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
background: rgba(0,0,0,0.85);
display: flex;
align-items: center;
justify-content: center;
color: #0f9;
font-size: 2rem;
font-weight: 700;
text-align: center;
padding: 1rem;
z-index: 1000;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s ease;
border-radius: 12px;
user-select: none;
backdrop-filter: blur(5px);
}
#gameOverModal.show {
opacity: 1;
pointer-events: auto;
}
#gameOverModal button {
margin-top: 1rem;
background: #0ff;
border: none;
border-radius: 12px;
padding: 12px 24px;
font-size: 1.3rem;
font-weight: 700;
color: #000;
cursor: pointer;
box-shadow: 0 0 25px #0ff;
transition: background 0.3s, box-shadow 0.3s, transform 0.2s;
}
#gameOverModal button:hover,
#gameOverModal button:focus-visible {
background: #0cc;
box-shadow: 0 0 40px #0cc;
outline: none;
transform: scale(1.05);
}
#gameOverModal button:active {
background: #099;
box-shadow: inset 0 0 30px #099;
transform: scale(0.95);
}
.modal-content {
background: rgba(10, 30, 30, 0.95);
border: 3px solid #0f9;
border-radius: 20px;
padding: 2rem;
max-width: 90%;
box-shadow: 0 0 50px rgba(0, 255, 153, 0.5);
}
.power-up-indicator {
display: inline-block;
width: 20px;
height: 20px;
border-radius: 50%;
margin: 0 5px;
vertical-align: middle;
box-shadow: 0 0 8px currentColor;
}
/* Pause Overlay */
#pauseOverlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
display: flex;
align-items: center;
justify-content: center;
color: #0ff;
font-size: 3rem;
font-weight: 700;
z-index: 500;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s ease;
border-radius: 20px;
text-shadow: 0 0 20px #0ff;
backdrop-filter: blur(3px);
}
#pauseOverlay.show {
opacity: 1;
pointer-events: auto;
}
/* Instructions */
#instructions {
margin-top: 15px;
text-align: center;
font-size: 0.9rem;
max-width: 90vmin;
color: rgba(0, 255, 153, 0.7);
line-height: 1.5;
}
.highlight {
color: #0ff;
font-weight: bold;
}
Your code is quite solid already with clean structure, nice visual effects, accessibility, and interaction design. Below, I provide an improved/refined version with enhancements focusing on:
<!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 */
*, *::before, *::after {
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;
touch-action: manipulation;
}
@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, 0 0 30px rgba(0, 255, 153, 0.2);
touch-action: none;
user-select: none;
outline: none;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
display: block;
background: #111;
border-radius: 20px;
}
/* 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;
display: flex;
justify-content: center;
gap: 20px;
flex-wrap: wrap;
}
#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;
}
.score-container {
display: flex;
flex-direction: column;
align-items: center;
min-width: 120px;
background: rgba(0, 20, 15, 0.7);
padding: 8px 16px;
border-radius: 12px;
border: 1px solid #0f9;
box-shadow: 0 0 10px rgba(0, 255, 153, 0.3);
}
.score-label {
font-size: 0.9rem;
opacity: 0.8;
margin-bottom: 4px;
letter-spacing: 0.1em;
}
/* 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, outline-offset 0.2s;
user-select: none;
color: #000;
outline-offset: 2px;
outline-color: transparent;
outline-style: solid;
}
.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;
}
}
/* Top Control Bar */
#top-controls {
display: flex;
justify-content: space-between;
width: 90vmin;
max-width: 400px;
margin-bottom: 12px;
gap: 12px;
}
#top-controls .btn {
flex: 1;
padding: 10px 0;
font-size: 1.1rem;
}
#difficulty {
background: #0f9;
color: #000;
border: none;
border-radius: 12px;
padding: 0 15px;
font-size: 1.1rem;
font-weight: 700;
box-shadow: 0 0 20px #0f9;
cursor: pointer;
outline: none;
text-align: center;
transition: box-shadow 0.3s ease;
}
#difficulty:focus-visible {
outline: 2px solid #0cffaa;
box-shadow: 0 0 30px #0cffaa;
}
#difficulty option {
background: #111;
color: #0f9;
}
/* Game Over Modal */
#gameOverModal {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.85);
display: flex;
align-items: center;
justify-content: center;
color: #0f9;
font-size: 2rem;
font-weight: 700;
text-align: center;
padding: 1rem;
z-index: 1000;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s ease;
border-radius: 12px;
user-select: none;
backdrop-filter: blur(5px);
}
#gameOverModal.show {
opacity: 1;
pointer-events: auto;
}
#gameOverModal button {
margin-top: 1rem;
background: #0ff;
border: none;
border-radius: 12px;
padding: 12px 24px;
font-size: 1.3rem;
font-weight: 700;
color: #000;
cursor: pointer;
box-shadow: 0 0 25px #0ff;
transition: background 0.3s, box-shadow 0.3s, transform 0.2s;
}
#gameOverModal button:hover,
#gameOverModal button:focus-visible {
background: #0cc;
box-shadow: 0 0 40px #0cc;
outline: none;
transform: scale(1.05);
}
#gameOverModal button:active {
background: #099;
box-shadow: inset 0 0 30px #099;
transform: scale(0.95);
}
.modal-content {
background: rgba(10, 30, 30, 0.95);
border: 3px solid #0f9;
border-radius: 20px;
padding: 2rem;
max-width: 90%;
box-shadow: 0 0 50px rgba(0, 255, 153, 0.5);
}
.power-up-indicator {
display: inline-block;
width: 20px;
height: 20px;
border-radius: 50%;
margin: 0 5px;
vertical-align: middle;
box-shadow: 0 0 8px currentColor;
}
/* Pause Overlay */
#pauseOverlay {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.7);
display: flex;
align-items: center;
justify-content: center;
color: #0ff;
font-size: 3rem;
font-weight: 700;
z-index: 500;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s ease;
border-radius: 20px;
text-shadow: 0 0 20px #0ff;
backdrop-filter: blur(3px);
user-select: none;
}
#pauseOverlay.show {
opacity: 1;
pointer-events: auto;
}
/* Instructions */
#instructions {
margin-top: 15px;
text-align: center;
font-size: 0.9rem;
max-width: 90vmin;
color: rgba(0, 255, 153, 0.7);
line-height: 1.5;
user-select: none;
}
.highlight {
color: #0ff;
font-weight: bold;
}
/* Power-up timer text */
#powerupTimerText {
position: absolute;
top: 12px;
right: 12px;
font-weight: 700;
color: #0ff;
text-shadow: 0 0 10px #0ff;
user-select: none;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
transition: opacity 0.3s ease;
pointer-events: none;
font-size: 1rem;
}
#powerupTimerText.hidden {
opacity: 0;
pointer-events: none;
}
</style>
</head>
<body>
<div id="top-controls">
<button id="pauseBtn" class="btn" type="button" aria-label="Pause game" aria-pressed="false">⏸️ Pause</button>
<select id="difficulty" aria-label="Game difficulty">
<option value="easy">Easy</option>
<option value="medium" selected>Medium</option>
<option value="hard">Hard</option>
<option value="insane">Insane</option>
</select>
<button id="restartBtn" class="btn" type="button" aria-label="Restart game">🔄 Restart</button>
</div>
<main id="game" role="region" aria-label="Snake game area" tabindex="0">
<canvas id="canvas" aria-live="polite" aria-label="Game canvas"></canvas>
<div id="pauseOverlay" aria-live="assertive" aria-atomic="true">PAUSED</div>
<div id="powerupTimerText" class="hidden" aria-live="polite" aria-atomic="true"></div>
</main>
<div id="scoreboard" aria-live="polite" aria-atomic="true" role="status">
<div class="score-container">
<div class="score-label">SCORE</div>
<div id="currentScore" aria-live="off">0</div>
</div>
<div class="score-container">
<div class="score-label">HIGH SCORE</div>
<div id="highScore" aria-live="off">0</div>
</div>
<div class="score-container">
<div class="score-label">SPEED</div>
<div id="speedDisplay" aria-live="off">10</div>
</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>
<div id="instructions">
<div>
Collect <span class="highlight">apples</span> for points. Avoid walls and yourself!
</div>
<div>
Power-ups:
<span class="power-up-indicator" style="background: gold;" aria-label="Speed Boost"></span> Speed Boost
<span class="power-up-indicator" style="background: #ff00ff;" aria-label="Score Multiplier"></span> Score Multiplier
</div>
</div>
<!-- Game Over Modal -->
<div id="gameOverModal" role="dialog" aria-modal="true" aria-labelledby="gameOverTitle" aria-describedby="gameOverDesc" tabindex="-1">
<div class="modal-content">
<h2 id="gameOverTitle">Game Over!</h2>
<p id="gameOverDesc">Your final score is <span id="finalScore">0</span>.</p>
<button id="modalRestartBtn" type="button">Restart Game</button>
</div>
</div>
<!-- Sound effects (not using audio elements) -->
<script>
(function(){
'use strict';
/*
* Reuse a single AudioContext for all sounds,
* created on first user interaction to avoid browser auto-play restrictions.
*/
let audioCtx = null;
function getAudioContext() {
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
return audioCtx;
}
function playSound({ type='sine', freqStart=440, freqEnd=880, duration=0.3, gainStart=0.3, gainEnd=0.01 }) {
try {
const ctx = getAudioContext();
const oscillator = ctx.createOscillator();
const gainNode = ctx.createGain();
oscillator.type = type;
oscillator.frequency.setValueAtTime(freqStart, ctx.currentTime);
oscillator.frequency.exponentialRampToValueAtTime(freqEnd, ctx.currentTime + duration);
gainNode.gain.setValueAtTime(gainStart, ctx.currentTime);
gainNode.gain.exponentialRampToValueAtTime(gainEnd, ctx.currentTime + duration);
oscillator.connect(gainNode);
gainNode.connect(ctx.destination);
oscillator.start();
oscillator.stop(ctx.currentTime + duration);
// Clean up oscillator and gainNode disconnected automatically after stop
} catch (e) {
// Silence errors, often triggered if called before user gesture to start audio
}
}
/**
* Specific sound effects using playSound helper
*/
function generateEatSound() {
playSound({ type: 'sine', freqStart: 523.25, freqEnd: 1046.5, duration: 0.3, gainStart: 0.3, gainEnd: 0.01 });
}
function generatePowerSound() {
playSound({ type: 'sawtooth', freqStart: 220, freqEnd: 880, duration: 0.4, gainStart: 0.3, gainEnd: 0.01 });
}
function generateGameOverSound() {
playSound({ type: 'square', freqStart: 392, freqEnd: 130.81, duration: 0.8, gainStart: 0.4, gainEnd: 0.01 });
}
// DOM 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 speedEl = document.getElementById('speedDisplay');
const sb = document.getElementById('scoreboard');
const btns = document.querySelectorAll('.btn');
const restartBtn = document.getElementById('restartBtn');
const pauseBtn = document.getElementById('pauseBtn');
const difficulty = document.getElementById('difficulty');
const gameOverModal = document.getElementById('gameOverModal');
const pauseOverlay = document.getElementById('pauseOverlay');
const finalScoreEl = document.getElementById('finalScore');
const modalRestartBtn = document.getElementById('modalRestartBtn');
const powerupTimerText = document.getElementById('powerupTimerText');
// Offscreen canvas for grid rendering to optimize draw calls
const gridCanvas = document.createElement('canvas');
const gridCtx = gridCanvas.getContext('2d');
// Game Config & State variables
const tileCount = 24;
let gridSize;
let fps = 10;
const maxApples = 3;
let snake, velocity, nextVel, apples, powerUps, score, gameOver, isPaused;
let comboCounter, lastAppleTime, hue;
let effects;
let highScore = parseInt(localStorage.getItem('snakeHighScore'), 10) || 0;
let snakeTrail = [];
let powerUpActive = null;
let powerUpTimer = 0;
const powerUpDuration = 5000; // milliseconds
// Timing for fixed FPS control using delta accumulator
let lastTime = 0;
let delta = 0;
let interval = 1000 / fps;
// Power-up types with effect and reverse effect functions
const POWERUP_TYPES = {
SPEED_BOOST: {
color: 'gold',
effect: () => {
fps *= 1.5;
interval = 1000 / fps;
},
reverse: () => {
fps /= 1.5;
interval = 1000 / fps;
}
},
SCORE_MULTIPLIER: {
color: '#ff00ff',
effect: () => {
// No direct speed effect, logic could be added for multiplier
scoreMultiplier = 2;
},
reverse: () => {
scoreMultiplier = 1;
}
}
};
let scoreMultiplier = 1;
// Initialize or reset game state
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 = [];
powerUps = [];
score = 0;
comboCounter = 0;
lastAppleTime = 0;
hue = 0;
effects = { score: [], particles: [] };
gameOver = false;
isPaused = false;
powerUpActive = null;
powerUpTimer = 0;
snakeTrail = [];
fps = {
easy: 8,
medium: 10,
hard: 13,
insane: 16
}[difficulty.value] || 10;
interval = 1000 / fps;
scoreMultiplier = 1;
scoreEl.textContent = score;
speedEl.textContent = Math.round(fps);
pauseOverlay.classList.remove('show');
powerupTimerText.classList.add('hidden');
gameOverModal.classList.remove('show');
pauseBtn.textContent = '⏸️ Pause';
pauseBtn.setAttribute('aria-pressed', 'false');
spawnApples();
game.focus();
}
// Handle dynamic canvas sizing (square game area)
function resizeCanvas(){
const size = game.clientWidth;
canvas.width = size;
canvas.height = size;
gridSize = size / tileCount;
// Pre-render grid to offscreen canvas only once per resize
gridCanvas.width = size;
gridCanvas.height = size;
gridCtx.clearRect(0, 0, gridCanvas.width, gridCanvas.height);
gridCtx.strokeStyle = '#222';
gridCtx.lineWidth = 1;
for(let i=0; i<=tileCount; i++){
const pos = i * gridSize + 0.5; // 0.5 to avoid blurry lines
gridCtx.beginPath();
// vertical line
gridCtx.moveTo(pos, 0);
gridCtx.lineTo(pos, gridCanvas.height);
// horizontal line
gridCtx.moveTo(0, pos);
gridCtx.lineTo(gridCanvas.width, pos);
gridCtx.stroke();
}
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// Helper functions
function colorGradient(isSnake){
hue = (hue + 2) % 360;
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)
&& !powerUps.some(p=>p.x===x&&p.y===y);
}
// Apple and power-up spawning
function spawnApples(){
while(apples.length < maxApples){
const p = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount),
type: 'apple'
};
if(isEmpty(p.x, p.y)) apples.push(p);
}
// Occasionally spawn power-up (20% chance) if no power-up active on map
if (powerUps.length === 0 && Math.random() < 0.2) {
const types = Object.keys(POWERUP_TYPES);
const type = types[Math.floor(Math.random() * types.length)];
const p = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount),
type: type,
color: POWERUP_TYPES[type].color
};
if(isEmpty(p.x, p.y)) powerUps.push(p);
}
}
// Effects (score pop-up, particles, flash)
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, color, count=12, size=6){
for(let i=0;i<count;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()*size + (size/2),
color: color || `hsla(${Math.random()*360},100%,60%,1)`
});
}
}
function updateEffects(){
// Use reverse loops to safely remove
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);
}
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.dy += 0.1; // gravity
if(p.alpha <= 0) effects.particles.splice(i,1);
}
}
function flashScore(){
sb.classList.add('flash');
setTimeout(()=> sb.classList.remove('flash'), 200);
generateEatSound();
}
// Game update per tick
function update(){
if(gameOver || isPaused) return;
// Update power-up timer
if (powerUpActive) {
powerUpTimer -= interval;
if (powerUpTimer <= 0) {
POWERUP_TYPES[powerUpActive].reverse();
powerUpActive = null;
powerUpTimer = 0;
powerupTimerText.classList.add('hidden');
speedEl.textContent = Math.round(fps);
} else {
// Update power-up timer display
powerupTimerText.textContent = `POWER: ${Math.ceil(powerUpTimer / 1000)}s`;
powerupTimerText.classList.remove('hidden');
}
} else {
powerupTimerText.classList.add('hidden');
}
// Apply direction change if valid (no 180-degree turn)
if ((nextVel.x !== -velocity.x || nextVel.y !== -velocity.y)
&& (nextVel.x !== velocity.x || nextVel.y !== velocity.y)) {
velocity = nextVel;
}
// Calculate new head position (wrap around)
const head = {
x: (snake[0].x + velocity.x + tileCount) % tileCount,
y: (snake[0].y + velocity.y + tileCount) % tileCount
};
// Track a short trail for nice tail effect
snakeTrail.push({...snake[0]});
if (snakeTrail.length > 5) snakeTrail.shift();
// Check collision with self = game over
if(snake.some(p => p.x === head.x && p.y === head.y)){
gameOver = true;
showGameOver();
return;
}
snake.unshift(head);
let ate = false;
let powerUpCollected = false;
// Check if apple eaten
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 baseGain = 10;
let gain = baseGain + timeBonus + comboBonus;
gain *= scoreMultiplier;
gain = Math.round(gain);
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, '#0f9', 20, 8);
flashScore();
apples.splice(i,1);
spawnApples();
ate = true;
break;
}
}
// Check if power-up collected
for(let i=0; i<powerUps.length; i++){
if(powerUps[i].x === head.x && powerUps[i].y === head.y){
const type = powerUps[i].type;
// Reverse existing power-up effects if any
if(powerUpActive) {
POWERUP_TYPES[powerUpActive].reverse();
}
POWERUP_TYPES[type].effect();
powerUpActive = type;
powerUpTimer = powerUpDuration;
addParticles(head.x, head.y, POWERUP_TYPES[type].color, 30, 10);
generatePowerSound();
powerUps.splice(i,1);
powerUpCollected = true;
speedEl.textContent = Math.round(fps);
break;
}
}
if(!ate && !powerUpCollected){
comboCounter = 0;
snake.pop();
}
}
// Drawing function
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw grid background from offscreen canvas
ctx.drawImage(gridCanvas, 0, 0);
// Draw snake trail with fading squares
for (let i = 0; i < snakeTrail.length; i++) {
const t = snakeTrail[i];
const px = t.x * gridSize, py = t.y * gridSize;
const size = gridSize * (0.4 + (i * 0.12));
const offset = (gridSize - size) / 2;
ctx.save();
ctx.globalAlpha = 0.3 - (i * 0.05);
ctx.fillStyle = `hsl(${(hue + i*10) % 360}, 100%, 60%)`;
ctx.shadowColor = '#0ff';
ctx.shadowBlur = 15;
roundedRect(px + offset, py + offset, size, size, 5);
ctx.restore();
}
// Draw power-ups with animation and shadows
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() / 1000);
ctx.shadowColor = p.color;
ctx.shadowBlur = 20;
if (p.type === 'SPEED_BOOST') {
// Lightning bolt shape
ctx.fillStyle = p.color;
ctx.beginPath();
ctx.moveTo(-gridSize*0.2, -gridSize*0.3);
ctx.lineTo(0, 0);
ctx.lineTo(gridSize*0.2, gridSize*0.3);
ctx.lineTo(0, gridSize*0.1);
ctx.lineTo(gridSize*0.2, gridSize*0.4);
ctx.lineTo(-gridSize*0.1, gridSize*0.4);
ctx.lineTo(0, gridSize*0.1);
ctx.lineTo(-gridSize*0.2, -gridSize*0.1);
ctx.closePath();
ctx.fill();
} else {
// Star
ctx.fillStyle = p.color;
ctx.beginPath();
for (let i = 0; i < 10; i++) {
const angle = i * Math.PI / 5;
const radius = i % 2 === 0 ? gridSize * 0.3 : gridSize * 0.15;
ctx.lineTo(Math.cos(angle) * radius, Math.sin(angle) * radius);
}
ctx.closePath();
ctx.fill();
}
ctx.restore();
});
// Draw apples with gradient and shadow
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();
});
// Draw snake with head eyes
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 ? 25 : 18);
roundedRect(px+2, py+2, gridSize-4, gridSize-4, 8);
// Draw eyes on head
if (i === 0) {
ctx.fillStyle = '#000';
// Eye positions relative to velocity
const eyeOffsetX = velocity.x === 1 ? gridSize - 8 : velocity.x === -1 ? 8 : gridSize/2;
const eyeOffsetY = velocity.y === 1 ? gridSize - 8 : velocity.y === -1 ? 8 : gridSize/2;
const eyeSpacing = 4;
// Left eye
ctx.beginPath();
ctx.arc(px + eyeOffsetX, py + eyeOffsetY - eyeSpacing, 4, 0, 2 * Math.PI);
ctx.fill();
// Right eye
ctx.beginPath();
ctx.arc(px + eyeOffsetX, py + eyeOffsetY + eyeSpacing, 4, 0, 2 * Math.PI);
ctx.fill();
}
ctx.restore();
});
// Draw effects
effects.particles.forEach(p=>{
// hsla to rgba conversion with alpha
const color = p.color.replace(/hsla?\(([^)]+)\)/, (match, vals) => {
const parts = vals.split(',').map(v => v.trim());
const h = parts[0], s = parts[1], l = parts[2];
return `hsla(${h},${s},${l},${p.alpha})`;
});
ctx.fillStyle = 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 Arial`;
ctx.textAlign = 'center';
ctx.shadowColor = '#0f9';
ctx.shadowBlur = 10;
ctx.fillText(e.text, e.x, e.y);
});
}
// Touch input handling for swipe gestures - improved to handle multi-touch cancelled gracefully
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 };
} else {
touchStart = null;
}
}, { passive: true });
canvas.addEventListener('touchmove', e=>{
if(!touchStart || isPaused) return;
if (e.touches.length !== 1) {
touchStart = null;
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;
if (navigator.vibrate) navigator.vibrate(50);
}
}, { passive: true });
canvas.addEventListener('touchend', () => { touchStart = null; });
canvas.addEventListener('touchcancel', () => { touchStart = null; });
// Directional buttons
btns.forEach(b => b.addEventListener('click', () => {
if (!isPaused) changeDir(b.dataset.dir);
}));
// Keyboard arrow keys & WASD controls + pause toggle (P or space)
window.addEventListener('keydown', e => {
if(gameOver) return; // ignore all input if game over
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',
p: 'pause',
P: 'pause',
' ': 'pause'
};
const action = keyMap[e.key];
if(action) {
e.preventDefault();
if (action === 'pause') {
togglePause();
} else if (!isPaused) {
changeDir(action);
}
}
});
// Change snake moving direction
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 toggle logic
function togglePause() {
if(gameOver) return;
isPaused = !isPaused;
pauseBtn.textContent = isPaused ? '▶️ Resume' : '⏸️ Pause';
pauseBtn.setAttribute('aria-pressed', isPaused.toString());
pauseOverlay.classList.toggle('show', isPaused);
if (!isPaused) game.focus();
}
pauseBtn.addEventListener('click', togglePause);
// Game over visible & logic
function showGameOver(){
finalScoreEl.textContent = score;
gameOverModal.classList.add('show');
modalRestartBtn.focus();
generateGameOverSound();
}
// Restart game logic
function restartGame() {
if (powerUpActive) {
POWERUP_TYPES[powerUpActive].reverse();
}
initGame();
}
restartBtn.addEventListener('click', () => {
restartGame();
game.focus();
});
modalRestartBtn.addEventListener('click', () => {
restartGame();
game.focus();
});
// Difficulty selection changed
difficulty.addEventListener('change', function() {
let newFps = {
easy: 8,
medium: 10,
hard: 13,
insane: 16
}[this.value] || 10;
// If speed boost active, adjust accordingly
if (powerUpActive === 'SPEED_BOOST') {
fps = newFps * 1.5;
} else {
fps = newFps;
}
interval = 1000 / fps;
speedEl.textContent = Math.round(fps);
if (!gameOver && !isPaused) game.focus();
});
// Main game loop with requestAnimationFrame & fixed timestep
function loop(timestamp = 0) {
if(!lastTime) lastTime = timestamp;
delta += timestamp - lastTime;
lastTime = timestamp;
while(delta >= interval){
update();
updateEffects();
delta -= interval;
}
draw();
requestAnimationFrame(loop);
}
// Start game on first user interaction to unlock AudioContext
function unlockAudioContext() {
if(audioCtx) return;
try {
getAudioContext();
// play slight silent buffer to unlock audio context in some browsers
const oscillator = audioCtx.createOscillator();
oscillator.connect(audioCtx.destination);
oscillator.start();
oscillator.stop(audioCtx.currentTime + 0.1);
} catch {}
}
window.addEventListener('click', unlockAudioContext, { once: true, passive: true });
window.addEventListener('keydown', unlockAudioContext, { once: true, passive: true });
// Initialize and start game loop
initGame();
requestAnimationFrame(loop);
})();
</script>
</body>
</html>
playSound generic function handles sound creation; eliminates duplicate code pattern.#game container, instead of canvas draw. This improves accessibility and visual consistency.aria-pressed attribute to reflect toggle state.let/const, included early returns, simplified some conditionals.aria-live attributes where relevant to inform screen readers when the game state/score changes.This results in a more performance-friendly, accessible, and maintainable game UI with an elegant style and interactive behavior. Let me know if you'd like me to also improve the game mechanics or add other advanced usability/accessibility features!
Not yet included in a published release.