Make the code better: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8">…
- User
Make the code better:
code - Assistant
- User
I want you to act like a senior software engineer. Make the game better
- Assistant
Make the code better:
I want you to act like a senior software engineer. Make the game better
body {
background: radial-gradient(circle at center, #0f0c29, #302b63, #24243e);
min-height: 100vh;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
color: white;
touch-action: none;
position: relative;
}
.game-container {
position: relative;
width: 100%;
max-width: 800px;
text-align: center;
padding: 20px;
z-index: 10;
}
.header {
margin-bottom: 20px;
text-shadow: 0 0 10px rgba(255, 255, 255, 0.6);
position: relative;
}
.header h1 {
font-size: 3.5rem;
margin-bottom: 5px;
background: linear-gradient(to right, #12c2e9, #c471ed, #f64f59);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
letter-spacing: 3px;
text-transform: uppercase;
font-weight: 900;
position: relative;
z-index: 2;
}
.header::after {
content: "";
position: absolute;
top: -15px;
left: 50%;
transform: translateX(-50%);
width: 200px;
height: 200px;
background: radial-gradient(circle, rgba(246, 79, 89, 0.4) 0%, transparent 70%);
z-index: 1;
animation: pulse 3s infinite;
}
.score-container {
display: flex;
justify-content: center;
gap: 30px;
margin-bottom: 10px;
position: relative;
z-index: 2;
}
.score-box {
background: rgba(0, 0, 0, 0.3);
padding: 12px 25px;
border-radius: 15px;
box-shadow: 0 5px 25px rgba(0, 0, 0, 0.5),
0 0 15px rgba(18, 194, 233, 0.4);
backdrop-filter: blur(6px);
min-width: 130px;
transition: transform 0.3s ease, box-shadow 0.3s ease;
border: 2px solid rgba(255, 255, 255, 0.1);
position: relative;
overflow: hidden;
}
.score-box:hover {
transform: scale(1.05);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.6),
0 0 20px rgba(18, 194, 233, 0.6);
}
.score-box::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
animation: shine 3s infinite;
}
.score-box h2 {
color: #c471ed;
font-size: 1.3rem;
margin-bottom: 6px;
letter-spacing: 1.2px;
}
.score-box p {
color: #12c2e9;
font-size: 2.2rem;
font-weight: 800;
text-shadow: 0 0 10px rgba(18, 194, 233, 0.7);
}
.game-board {
position: relative;
width: 100%;
height: 65vh;
max-height: 550px;
border-radius: 18px;
overflow: hidden;
box-shadow: 0 15px 40px rgba(0, 0, 0, 0.7),
0 0 25px rgba(246, 79, 89, 0.5);
margin: 0 auto 20px;
border: 3px solid rgba(255, 255, 255, 0.15);
transform: perspective(1000px) rotateX(5deg);
transition: transform 0.5s ease, box-shadow 0.5s ease;
}
.game-board:hover {
transform: perspective(1000px) rotateX(5deg) scale(1.01);
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.8),
0 0 35px rgba(246, 79, 89, 0.7);
}
#game3dContainer {
width: 100%;
height: 100%;
border-radius: 18px;
outline: none;
}
.controls {
display: flex;
justify-content: center;
margin-top: 15px;
gap: 20px;
}
.control-btn {
background: rgba(255, 255, 255, 0.1);
border: 2px solid rgba(255, 255, 255, 0.2);
border-radius: 50%;
width: 65px;
height: 65px;
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
color: white;
cursor: pointer;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4),
0 0 10px rgba(18, 194, 233, 0.4);
transition: all 0.2s ease;
user-select: none;
position: relative;
overflow: hidden;
z-index: 2;
}
.control-btn::before {
content: "";
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.2), transparent);
transform: rotate(45deg);
animation: shine 3s infinite;
}
.control-btn:active {
transform: scale(0.9);
background: rgba(255, 255, 255, 0.2);
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.4),
0 0 15px rgba(18, 194, 233, 0.6);
}
#pause {
background: rgba(246, 79, 89, 0.25);
border-color: rgba(246, 79, 89, 0.55);
color: #f64f59;
border-radius: 35px;
width: 140px;
font-size: 26px;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4),
0 0 10px rgba(246, 79, 89, 0.4);
}
.instructions {
margin-top: 18px;
font-size: 1.1rem;
line-height: 1.6;
color: rgba(255, 255, 255, 0.9);
max-width: 500px;
margin-left: auto;
margin-right: auto;
background: rgba(0, 0, 0, 0.2);
padding: 15px 25px;
border-radius: 15px;
border: 1px solid rgba(255, 255, 255, 0.15);
backdrop-filter: blur(5px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
position: relative;
z-index: 2;
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.9);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 20;
color: #f64f59;
font-weight: 700;
text-align: center;
padding: 20px;
font-size: 2rem;
border-radius: 18px;
backdrop-filter: blur(10px);
}
.overlay.hidden {
display: none;
}
.overlay h2 {
font-size: 3.5rem;
margin-bottom: 20px;
text-shadow: 0 0 15px rgba(246, 79, 89, 0.8);
animation: pulseText 2s infinite;
}
.overlay p {
max-width: 80%;
font-size: 1.4rem;
margin-bottom: 20px;
line-height: 1.6;
color: #c471ed;
}
.overlay button {
margin-top: 22px;
background: linear-gradient(to right, #12c2e9, #c471ed, #f64f59);
border: none;
padding: 16px 48px;
border-radius: 32px;
color: white;
font-size: 1.3rem;
font-weight: 700;
cursor: pointer;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4),
0 0 15px rgba(200, 200, 255, 0.6);
transition: all 0.3s ease;
letter-spacing: 1px;
position: relative;
overflow: hidden;
z-index: 2;
}
.overlay button::before {
content: "";
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.3), transparent);
transform: rotate(45deg);
animation: shine 3s infinite;
}
.overlay button:hover {
transform: scale(1.08);
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.6),
0 0 25px rgba(200, 200, 255, 0.8);
}
.swipe-hint {
position: absolute;
bottom: 20px;
left: 0;
width: 100%;
text-align: center;
font-size: 1.2rem;
color: rgba(255, 255, 255, 0.8);
animation: pulse 2s infinite;
text-shadow: 0 0 5px rgba(18, 194, 233, 0.7);
z-index: 2;
}
.particle {
position: absolute;
border-radius: 50%;
background: currentColor;
pointer-events: none;
opacity: 0;
animation: float 5s linear infinite;
box-shadow: 0 0 10px currentColor;
}
.glow {
position: absolute;
border-radius: 50%;
pointer-events: none;
opacity: 0.5;
animation: pulseGlow 3s infinite;
z-index: 1;
}
@keyframes float {
0% {
transform: translateY(0) translateX(0) scale(0.5);
opacity: 1;
}
100% {
transform: translateY(-1000px) translateX(100px) scale(1.5);
opacity: 0;
}
}
@keyframes pulse {
0% { opacity: 0.4; }
50% { opacity: 1; }
100% { opacity: 0.4; }
}
@keyframes pulseText {
0% { text-shadow: 0 0 15px rgba(246, 79, 89, 0.8); }
50% { text-shadow: 0 0 25px rgba(246, 79, 89, 1); }
100% { text-shadow: 0 0 15px rgba(246, 79, 89, 0.8); }
}
@keyframes shine {
0% { transform: translateX(-100%) rotate(45deg); }
100% { transform: translateX(100%) rotate(45deg); }
}
@keyframes pulseGlow {
0% { box-shadow: 0 0 10px rgba(18, 194, 233, 0.5); }
50% { box-shadow: 0 0 30px rgba(18, 194, 233, 0.8); }
100% { box-shadow: 0 0 10px rgba(18, 194, 233, 0.5); }
}
@media (max-width: 768px) {
.header h1 {
font-size: 2.8rem;
}
.score-box {
padding: 10px 20px;
min-width: 110px;
}
.score-box h2 {
font-size: 1.1rem;
}
.score-box p {
font-size: 1.8rem;
}
.control-btn {
width: 60px;
height: 60px;
font-size: 26px;
}
#pause {
width: 120px;
font-size: 24px;
}
.overlay h2 {
font-size: 2.8rem;
}
.overlay p {
font-size: 1.2rem;
}
.instructions {
font-size: 1rem;
padding: 12px 20px;
}
}
@media (max-width: 480px) {
.header h1 {
font-size: 2.2rem;
}
.score-box {
min-width: 90px;
padding: 8px 15px;
}
.score-box p {
font-size: 1.6rem;
}
.control-btn {
width: 55px;
height: 55px;
font-size: 24px;
}
#pause {
width: 110px;
font-size: 22px;
}
.overlay h2 {
font-size: 2.2rem;
}
.overlay p {
font-size: 1.1rem;
}
.instructions {
font-size: 0.95rem;
padding: 10px 15px;
}
}
</style>
<div class="game-board">
<div id="game3dContainer"></div>
<div class="overlay" id="startOverlay">
<h2>3D SNAKE ADVENTURE</h2>
<p>Swipe to control the snake in this 3D world! Eat colorful apples to grow. Snake wraps around walls. 3-5 apples at a time.</p>
<button id="startBtn">START GAME</button>
</div>
<div class="overlay hidden" id="gameOverOverlay">
<h2>GAME OVER</h2>
<p>Your final score: <span id="finalScore">0</span></p>
<button id="restartBtn">PLAY AGAIN</button>
</div>
<div class="swipe-hint">SWIPE TO MOVE THE SNAKE</div>
</div>
<div class="controls">
<button class="control-btn" id="pause">❚❚</button>
</div>
<div class="instructions">
<p>Eat the colorful apples to grow! Snake wraps around walls. 3-5 apples at a time. Swipe or use arrow keys to move.</p>
</div>
</div>
<script>
// Game variables
let scene, camera, renderer, snakeMeshes = [], appleMeshes = [];
let snake = [], apples = [];
let direction = 'right', nextDirection = 'right';
let score = 0, applesEaten = 0;
let gameSpeed = 8; // moves per second
let gameRunning = false;
let animationFrameId = null;
let lastRenderTime = null;
let gridWidth = 20, gridHeight = 15;
const gridSize = 1;
let particles = [];
let touchStartX, touchStartY;
let minApples = 3, maxApples = 5;
// Initialize Three.js scene
function initThreeScene() {
// Create scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a0a1f);
scene.fog = new THREE.Fog(0x0a0a1f, 15, 50);
// Create camera
camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.set(gridWidth/2, gridHeight * 1.5, gridHeight * 2);
camera.lookAt(gridWidth/2, 0, gridHeight/2);
// Create renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(document.querySelector('.game-board').clientWidth,
document.querySelector('.game-board').clientHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.getElementById('game3dContainer').appendChild(renderer.domElement);
// Add lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(gridWidth/2, gridHeight * 2, gridHeight/2);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
scene.add(directionalLight);
// Create ground
const groundGeometry = new THREE.PlaneGeometry(gridWidth * 1.2, gridHeight * 1.2);
const groundMaterial = new THREE.MeshPhongMaterial({
color: 0x1a1a2e,
shininess: 30,
side: THREE.DoubleSide,
emissive: 0x121230,
emissiveIntensity: 0.2
});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.set(gridWidth/2, -0.5, gridHeight/2);
ground.receiveShadow = true;
scene.add(ground);
// Create grid helper
const gridHelper = new THREE.GridHelper(
Math.max(gridWidth, gridHeight) * 1.2,
Math.max(gridWidth, gridHeight),
0x444466,
0x222244
);
gridHelper.position.set(gridWidth/2, 0.01, gridHeight/2);
gridHelper.material.opacity = 0.3;
gridHelper.material.transparent = true;
scene.add(gridHelper);
// Add star particles
const starGeometry = new THREE.BufferGeometry();
const starMaterial = new THREE.PointsMaterial({
color: 0xffffff,
size: 0.1,
sizeAttenuation: false
});
const starVertices = [];
for (let i = 0; i < 1000; i++) {
const x = (Math.random() - 0.5) * 2000;
const y = (Math.random() - 0.5) * 2000;
const z = (Math.random() - 0.5) * 2000;
starVertices.push(x, y, z);
}
starGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starVertices, 3));
const stars = new THREE.Points(starGeometry, starMaterial);
scene.add(stars);
}
// Initialize game
function initGame() {
// Reset snake
snake = [
{x: Math.floor(gridWidth / 2), y: Math.floor(gridHeight / 2)},
{x: Math.floor(gridWidth / 2) - 1, y: Math.floor(gridHeight / 2)},
{x: Math.floor(gridWidth / 2) - 2, y: Math.floor(gridHeight / 2)}
];
// Create snake meshes
createSnakeMeshes();
// Reset apples
apples = [];
spawnApples();
// Reset game state
direction = 'right';
nextDirection = 'right';
score = 0;
applesEaten = 0;
gameSpeed = 8;
gameRunning = false;
// Update UI
document.getElementById('score').textContent = score;
document.getElementById('apples').textContent = applesEaten;
document.getElementById('startOverlay').classList.remove('hidden');
document.getElementById('gameOverOverlay').classList.add('hidden');
document.getElementById('pause').textContent = '❚❚';
}
// Create snake meshes
function createSnakeMeshes() {
// Clear existing snake
snakeMeshes.forEach(segment => scene.remove(segment));
snakeMeshes = [];
// Create new snake segments
snake.forEach((segment, index) => {
const isHead = index === 0;
const size = isHead ? 0.8 : 0.7 - (index * 0.01);
const geometry = new THREE.SphereGeometry(size, 16, 16);
// Create gradient color for snake
let color;
if (isHead) {
color = new THREE.Color(0x4caf50);
} else {
const hue = 0.33 + 0.15 * (index / snake.length);
color = new THREE.Color().setHSL(hue, 0.7, 0.5);
}
const material = new THREE.MeshPhongMaterial({
color: color,
shininess: 50,
emissive: color,
emissiveIntensity: 0.1
});
const segmentMesh = new THREE.Mesh(geometry, material);
segmentMesh.position.set(segment.x, 0.4, segment.y);
segmentMesh.castShadow = true;
segmentMesh.receiveShadow = true;
snakeMeshes.push(segmentMesh);
scene.add(segmentMesh);
});
}
// Spawn apples
function spawnApples() {
// Clear existing apples
appleMeshes.forEach(apple => scene.remove(apple));
appleMeshes = [];
// Spawn apples to maintain 3-5
const currentCount = apples.length;
const targetCount = Math.min(maxApples, Math.max(minApples, Math.floor(Math.random() * (maxApples - minApples + 1)) + minApples));
const toSpawn = Math.max(0, targetCount - currentCount);
for (let i = 0; i < toSpawn; i++) {
const newApple = {
x: Math.floor(Math.random() * gridWidth),
y: Math.floor(Math.random() * gridHeight),
color: getRandomColor()
};
// Ensure apple doesn't spawn on snake
const collisionWithSnake = snake.some(s => s.x === newApple.x && s.y === newApple.y);
if (!collisionWithSnake) {
apples.push(newApple);
}
}
// Create apple meshes
createAppleMeshes();
}
// Create apple meshes
function createAppleMeshes() {
apples.forEach(apple => {
const geometry = new THREE.SphereGeometry(0.4, 16, 16);
const material = new THREE.MeshPhongMaterial({
color: apple.color,
shininess: 100,
emissive: apple.color,
emissiveIntensity: 0.2
});
const appleMesh = new THREE.Mesh(geometry, material);
appleMesh.position.set(apple.x, 0.4, apple.y);
appleMesh.castShadow = true;
appleMesh.receiveShadow = true;
appleMeshes.push(appleMesh);
scene.add(appleMesh);
// Add glow effect
const glowGeometry = new THREE.SphereGeometry(0.5, 16, 16);
const glowMaterial = new THREE.MeshBasicMaterial({
color: apple.color,
transparent: true,
opacity: 0.3,
side: THREE.BackSide
});
const glowMesh = new THREE.Mesh(glowGeometry, glowMaterial);
glowMesh.position.set(apple.x, 0.4, apple.y);
appleMeshes.push(glowMesh);
scene.add(glowMesh);
});
}
// Get random color
function getRandomColor() {
const colors = [
'#FF5252', '#FF4081', '#E040FB', '#7C4DFF',
'#536DFE', '#448AFF', '#40C4FF', '#18FFFF',
'#64FFDA', '#69F0AE', '#B2FF59', '#EEFF41'
];
return colors[Math.floor(Math.random() * colors.length)];
}
// Update game state
function update() {
// Apply next direction if valid (no 180 turns)
if (nextDirection) {
if (
(nextDirection === 'up' && direction !== 'down') ||
(nextDirection === 'down' && direction !== 'up') ||
(nextDirection === 'left' && direction !== 'right') ||
(nextDirection === 'right' && direction !== 'left')
) {
direction = nextDirection;
}
}
// Compute new head position
const head = {...snake[0]};
switch (direction) {
case 'up': head.y--; break;
case 'down': head.y++; break;
case 'left': head.x--; break;
case 'right': head.x++; break;
}
// Wrap positions
if (head.x < 0) head.x = gridWidth - 1;
else if (head.x >= gridWidth) head.x = 0;
if (head.y < 0) head.y = gridHeight - 1;
else if (head.y >= gridHeight) head.y = 0;
// Check collision with self
for (let i = 0; i < snake.length; i++) {
if (snake[i].x === head.x && snake[i].y === head.y) {
endGame();
return;
}
}
snake.unshift(head);
// Check if apple eaten
let ateApple = false;
for (let i = 0; i < apples.length; i++) {
if (apples[i].x === head.x && apples[i].y === head.y) {
// Remove apple and create particles
apples.splice(i, 1);
createParticles(head.x, head.y, apples[i].color);
// Update score
score += 10;
applesEaten++;
gameSpeed = Math.min(20, gameSpeed + 0.3);
document.getElementById('score').textContent = score;
document.getElementById('apples').textContent = applesEaten;
ateApple = true;
break;
}
}
if (!ateApple) {
snake.pop();
} else {
spawnApples();
createSnakeMeshes();
}
}
// Create particles when eating an apple
function createParticles(x, y, color) {
for (let i = 0; i < 30; i++) {
const particle = document.createElement('div');
particle.className = 'particle';
particle.style.left = `${x * (100 / gridWidth)}%`;
particle.style.top = `${y * (100 / gridHeight)}%`;
particle.style.width = `${Math.random() * 15 + 5}px`;
particle.style.height = particle.style.width;
particle.style.color = color;
particle.style.animationDuration = `${Math.random() * 1 + 0.5}s`;
document.body.appendChild(particle);
// Remove particle after animation
setTimeout(() => {
particle.remove();
}, 1000);
}
}
// Render the scene
function render() {
// Update snake positions
snakeMeshes.forEach((mesh, i) => {
mesh.position.set(snake[i].x, 0.4, snake[i].y);
// Add subtle animation to snake
if (gameRunning) {
const time = Date.now() * 0.002;
mesh.rotation.y = Math.sin(time + i * 0.3) * 0.1;
mesh.rotation.x = Math.cos(time + i * 0.2) * 0.05;
}
});
// Animate apples
appleMeshes.forEach(apple => {
if (apple.geometry.parameters.radius === 0.4) {
apple.rotation.y += 0.02;
apple.position.y = 0.4 + Math.sin(Date.now() * 0.002) * 0.1;
}
});
// Render the scene
renderer.render(scene, camera);
}
// Game loop
function gameLoop(timestamp) {
if (!gameRunning) return;
if (!lastRenderTime) lastRenderTime = timestamp;
const secondsSinceLastRender = (timestamp - lastRenderTime) / 1000;
const interval = 1 / gameSpeed;
if (secondsSinceLastRender >= interval) {
lastRenderTime = timestamp;
update();
}
render();
animationFrameId = requestAnimationFrame(gameLoop);
}
// Start game
function startGame() {
gameRunning = true;
lastRenderTime = null;
document.getElementById('startOverlay').classList.add('hidden');
animationFrameId = requestAnimationFrame(gameLoop);
}
// End game
function endGame() {
gameRunning = false;
cancelAnimationFrame(animationFrameId);
document.getElementById('finalScore').textContent = score;
document.getElementById('gameOverOverlay').classList.remove('hidden');
}
// Toggle pause
function togglePause() {
if (!gameRunning) return;
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
animationFrameId = null;
document.getElementById('pause').textContent = '▶';
} else {
animationFrameId = requestAnimationFrame(gameLoop);
document.getElementById('pause').textContent = '❚❚';
}
}
// Handle swipe gestures
function handleTouchStart(e) {
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
}
function handleTouchMove(e) {
if (!touchStartX || !touchStartY || !gameRunning) return;
const touchEndX = e.touches[0].clientX;
const touchEndY = e.touches[0].clientY;
const diffX = touchStartX - touchEndX;
const diffY = touchStartY - touchEndY;
// Determine swipe direction
if (Math.abs(diffX) > Math.abs(diffY)) {
// Horizontal swipe
if (diffX > 0) {
// Left swipe
nextDirection = 'left';
} else {
// Right swipe
nextDirection = 'right';
}
} else {
// Vertical swipe
if (diffY > 0) {
// Up swipe
nextDirection = 'up';
} else {
// Down swipe
nextDirection = 'down';
}
}
// Reset touch positions
touchStartX = null;
touchStartY = null;
}
// Initialize everything
function init() {
initThreeScene();
initGame();
// Add event listeners
document.getElementById('startBtn').addEventListener('click', startGame);
document.getElementById('restartBtn').addEventListener('click', () => {
initGame();
startGame();
});
document.getElementById('pause').addEventListener('click', togglePause);
// Keyboard controls
document.addEventListener('keydown', (e) => {
if (!gameRunning) return;
switch (e.key) {
case 'ArrowUp': nextDirection = 'up'; break;
case 'ArrowDown': nextDirection = 'down'; break;
case 'ArrowLeft': nextDirection = 'left'; break;
case 'ArrowRight': nextDirection = 'right'; break;
case ' ': togglePause(); break;
}
});
// Touch controls
const gameBoard = document.querySelector('.game-board');
gameBoard.addEventListener('touchstart', handleTouchStart, { passive: false });
gameBoard.addEventListener('touchmove', handleTouchMove, { passive: false });
// Create background particles
createBackgroundParticles();
}
// Create background particles
function createBackgroundParticles() {
for (let i = 0; i < 80; i++) {
const particle = document.createElement('div');
particle.className = 'particle';
particle.style.left = `${Math.random() * 100}%`;
particle.style.top = `${Math.random() * 100}%`;
const size = Math.random() * 10 + 3;
particle.style.width = `${size}px`;
particle.style.height = `${size}px`;
particle.style.color = getRandomColor();
particle.style.animationDuration = `${Math.random() * 10 + 5}s`;
particle.style.animationDelay = `${Math.random() * 5}s`;
document.body.appendChild(particle);
}
// Add glow effects
for (let i = 0; i < 5; i++) {
const glow = document.createElement('div');
glow.className = 'glow';
glow.style.left = `${Math.random() * 100}%`;
glow.style.top = `${Math.random() * 100}%`;
const size = Math.random() * 300 + 100;
glow.style.width = `${size}px`;
glow.style.height = `${size}px`;
glow.style.background = `radial-gradient(circle, ${getRandomColor()} 0%, transparent 70%)`;
document.body.appendChild(glow);
}
}
// Start the game when page loads
window.addEventListener('load', init);
</script>
Your code is quite well-structured and visually appealing. Here are some improvements to enhance readability, performance, maintainability, and user experience:
color (which is already removed).const/let properly.Here’s a revised version with inline comments explaining the changes and improvements:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Epic 3D Snake Adventure</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<style>
/* (Your original CSS unchanged for brevity; keep it as is) */
/* If you want, I can help minify or optimize CSS separately */
</style>
</head>
<body>
<div class="game-container">
<div class="header">
<h1>3D SNAKE ADVENTURE</h1>
<div class="score-container">
<div class="score-box" aria-live="polite" aria-atomic="true">
<h2>SCORE</h2>
<p id="score">0</p>
</div>
<div class="score-box" aria-live="polite" aria-atomic="true">
<h2>APPLES</h2>
<p id="apples">0</p>
</div>
</div>
</div>
<div class="game-board" role="application" aria-label="3D Snake Adventure game area" tabindex="0">
<div id="game3dContainer"></div>
<div class="overlay" id="startOverlay" role="dialog" aria-modal="true" aria-labelledby="startTitle" aria-describedby="startDesc">
<h2 id="startTitle">3D SNAKE ADVENTURE</h2>
<p id="startDesc">Swipe to control the snake in this 3D world! Eat colorful apples to grow. Snake wraps around walls. 3-5 apples at a time.</p>
<button id="startBtn" aria-label="Start game">START GAME</button>
</div>
<div class="overlay hidden" id="gameOverOverlay" role="dialog" aria-modal="true" aria-labelledby="gameOverTitle" aria-describedby="finalScoreDesc">
<h2 id="gameOverTitle">GAME OVER</h2>
<p>Your final score: <span id="finalScore" aria-live="polite" aria-atomic="true">0</span></p>
<button id="restartBtn" aria-label="Play again">PLAY AGAIN</button>
</div>
<div class="swipe-hint" aria-hidden="true">SWIPE TO MOVE THE SNAKE</div>
</div>
<div class="controls">
<button class="control-btn" id="pause" aria-pressed="false" aria-label="Pause game">❚❚</button>
</div>
<div class="instructions" aria-live="polite">
<p>Eat the colorful apples to grow! Snake wraps around walls. 3-5 apples at a time. Swipe or use arrow keys to move.</p>
</div>
</div>
<script>
(() => {
// Cache DOM elements for performance
const scoreEl = document.getElementById('score');
const applesEl = document.getElementById('apples');
const startOverlay = document.getElementById('startOverlay');
const gameOverOverlay = document.getElementById('gameOverOverlay');
const finalScoreEl = document.getElementById('finalScore');
const pauseBtn = document.getElementById('pause');
const startBtn = document.getElementById('startBtn');
const restartBtn = document.getElementById('restartBtn');
const game3dContainer = document.getElementById('game3dContainer');
// Game constants and variables
const gridWidth = 20;
const gridHeight = 15;
const minApples = 3;
const maxApples = 5;
const gridSize = 1;
let scene, camera, renderer;
let snakeMeshes = [];
let appleMeshes = [];
let snake = [];
let apples = [];
let direction = 'right';
let nextDirection = 'right';
let score = 0;
let applesEaten = 0;
let gameSpeed = 8; // moves per second
let gameRunning = false;
let animationFrameId = null;
let lastRenderTime = 0;
let touchStartX = null;
let touchStartY = null;
let appleColors = [
'#FF5252', '#FF4081', '#E040FB', '#7C4DFF',
'#536DFE', '#448AFF', '#40C4FF', '#18FFFF',
'#64FFDA', '#69F0AE', '#B2FF59', '#EEFF41'
];
// Utility: get random color from appleColors
function getRandomColor() {
return appleColors[Math.floor(Math.random() * appleColors.length)];
}
// Initialize Three.js scene and renderer
function initThreeScene() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a0a1f);
scene.fog = new THREE.Fog(0x0a0a1f, 15, 50);
camera = new THREE.PerspectiveCamera(
75,
game3dContainer.clientWidth / game3dContainer.clientHeight,
0.1,
1000
);
camera.position.set(gridWidth / 2, gridHeight * 1.5, gridHeight * 2);
camera.lookAt(gridWidth / 2, 0, gridHeight / 2);
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(game3dContainer.clientWidth, game3dContainer.clientHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
game3dContainer.appendChild(renderer.domElement);
// Add lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(gridWidth / 2, gridHeight * 2, gridHeight / 2);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
scene.add(directionalLight);
// Create ground plane
const groundGeometry = new THREE.PlaneGeometry(gridWidth * 1.2, gridHeight * 1.2);
const groundMaterial = new THREE.MeshPhongMaterial({
color: 0x1a1a2e,
shininess: 30,
side: THREE.DoubleSide,
emissive: 0x121230,
emissiveIntensity: 0.2
});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.set(gridWidth / 2, -0.5, gridHeight / 2);
ground.receiveShadow = true;
scene.add(ground);
// Grid helper for visual reference
const gridHelper = new THREE.GridHelper(
Math.max(gridWidth, gridHeight) * 1.2,
Math.max(gridWidth, gridHeight),
0x444466,
0x222244
);
gridHelper.position.set(gridWidth / 2, 0.01, gridHeight / 2);
gridHelper.material.opacity = 0.3;
gridHelper.material.transparent = true;
scene.add(gridHelper);
// Add star particles (fixed once)
const starGeometry = new THREE.BufferGeometry();
const starMaterial = new THREE.PointsMaterial({
color: 0xffffff,
size: 0.1,
sizeAttenuation: false
});
const starVertices = [];
for (let i = 0; i < 1000; i++) {
starVertices.push(
(Math.random() - 0.5) * 2000,
(Math.random() - 0.5) * 2000,
(Math.random() - 0.5) * 2000
);
}
starGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starVertices, 3));
const stars = new THREE.Points(starGeometry, starMaterial);
scene.add(stars);
}
// Resize renderer & camera on window resize
function onWindowResize() {
const width = game3dContainer.clientWidth;
const height = game3dContainer.clientHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
// Reset and initialize the snake game state
function initGame() {
// Clear previous snake & apples from scene
snakeMeshes.forEach((mesh) => scene.remove(mesh));
appleMeshes.forEach((mesh) => scene.remove(mesh));
snakeMeshes = [];
appleMeshes = [];
apples = [];
// Initialize snake centered horizontally, middle vertically
const startX = Math.floor(gridWidth / 2);
const startY = Math.floor(gridHeight / 2);
snake = [{ x: startX, y: startY }];
// Initial length 3 - extending left
for (let i = 1; i < 3; i++) {
snake.push({ x: startX - i, y: startY });
}
createSnakeMeshes();
spawnApples();
direction = 'right';
nextDirection = 'right';
score = 0;
applesEaten = 0;
gameSpeed = 8;
gameRunning = false;
lastRenderTime = 0;
updateUI();
startOverlay.classList.remove('hidden');
gameOverOverlay.classList.add('hidden');
pauseBtn.textContent = '❚❚';
pauseBtn.setAttribute('aria-pressed', 'false');
}
// Create visible snake segments meshes
function createSnakeMeshes() {
// Remove old meshes
snakeMeshes.forEach(mesh => scene.remove(mesh));
snakeMeshes = [];
// Create new meshes for snake parts
snake.forEach((segment, index) => {
const isHead = index === 0;
const size = isHead ? 0.8 : 0.7 - index * 0.01;
const geometry = new THREE.SphereGeometry(size, 16, 16);
let color;
if (isHead) {
color = new THREE.Color(0x4caf50);
} else {
// Smooth gradient along snake body based on position
const hue = 0.33 + 0.15 * (index / snake.length);
color = new THREE.Color().setHSL(hue, 0.7, 0.5);
}
const material = new THREE.MeshPhongMaterial({
color: color,
shininess: 50,
emissive: color,
emissiveIntensity: 0.1
});
const segmentMesh = new THREE.Mesh(geometry, material);
segmentMesh.position.set(segment.x, 0.4, segment.y);
segmentMesh.castShadow = true;
segmentMesh.receiveShadow = true;
snakeMeshes.push(segmentMesh);
scene.add(segmentMesh);
});
}
// Spawn apples ensuring they do not spawn on the snake
function spawnApples() {
// Remove old apple meshes
appleMeshes.forEach(mesh => scene.remove(mesh));
appleMeshes = [];
apples = [];
// Randomize number of apples within range
const appleCount = Math.floor(Math.random() * (maxApples - minApples + 1)) + minApples;
// Try spawning until desired count is achieved
while (apples.length < appleCount) {
const x = Math.floor(Math.random() * gridWidth);
const y = Math.floor(Math.random() * gridHeight);
// Ensure not colliding with snake or existing apples
const collision =
snake.some(s => s.x === x && s.y === y) ||
apples.some(a => a.x === x && a.y === y);
if (!collision) {
apples.push({ x, y, color: getRandomColor() });
}
}
createAppleMeshes();
}
function createAppleMeshes() {
apples.forEach(apple => {
// Apple Sphere
const geometry = new THREE.SphereGeometry(0.4, 16, 16);
const material = new THREE.MeshPhongMaterial({
color: apple.color,
shininess: 100,
emissive: apple.color,
emissiveIntensity: 0.2
});
const appleMesh = new THREE.Mesh(geometry, material);
appleMesh.position.set(apple.x, 0.4, apple.y);
appleMesh.castShadow = true;
appleMesh.receiveShadow = true;
appleMeshes.push(appleMesh);
scene.add(appleMesh);
// Glow effect
const glowGeometry = new THREE.SphereGeometry(0.5, 16, 16);
const glowMaterial = new THREE.MeshBasicMaterial({
color: apple.color,
transparent: true,
opacity: 0.3,
side: THREE.BackSide
});
const glowMesh = new THREE.Mesh(glowGeometry, glowMaterial);
glowMesh.position.set(apple.x, 0.4, apple.y);
appleMeshes.push(glowMesh);
scene.add(glowMesh);
});
}
// Update UI elements for score and apples eaten
function updateUI() {
scoreEl.textContent = score;
applesEl.textContent = applesEaten;
}
function update() {
// Validate and apply next direction, prevent 180-turns
if (
(nextDirection === 'up' && direction !== 'down') ||
(nextDirection === 'down' && direction !== 'up') ||
(nextDirection === 'left' && direction !== 'right') ||
(nextDirection === 'right' && direction !== 'left')
) {
direction = nextDirection;
}
// Compute new snake head position
let head = { ...snake[0] };
switch (direction) {
case 'up': head.y -= 1; break;
case 'down': head.y += 1; break;
case 'left': head.x -= 1; break;
case 'right': head.x += 1; break;
}
// Wrap around edges
head.x = (head.x + gridWidth) % gridWidth;
head.y = (head.y + gridHeight) % gridHeight;
// Check self-collision (skip head at index 0)
for (let i = 0; i < snake.length; i++) {
if (snake[i].x === head.x && snake[i].y === head.y) {
endGame();
return;
}
}
// Insert new head position
snake.unshift(head);
// Check if apple eaten
const appleIndex = apples.findIndex(a => a.x === head.x && a.y === head.y);
if (appleIndex !== -1) {
const eatenApple = apples[appleIndex];
// Create particles at apple position
createParticles(head.x, head.y, eatenApple.color);
// Update score and apples eaten
score += 10;
applesEaten++;
// Speed up game gradually
gameSpeed = Math.min(20, gameSpeed + 0.3);
// Remove eaten apple
apples.splice(appleIndex, 1);
// Respawn apples to maintain count
spawnApples();
// Update snake meshes to reflect growth
createSnakeMeshes();
// Update UI
updateUI();
} else {
// Remove snake tail if no apple eaten (normal move)
snake.pop();
}
}
// Create visual particles on eating apples
function createParticles(gridX, gridY, color) {
const rect = game3dContainer.getBoundingClientRect();
const particleCount = 30;
const particles = [];
for (let i = 0; i < particleCount; i++) {
const particle = document.createElement('div');
particle.className = 'particle';
// Position relative to game board
particle.style.position = 'absolute';
// Calculate % position for better responsiveness
particle.style.left = `${(gridX / gridWidth) * 100 + Math.random() * 4 - 2}%`;
particle.style.top = `${(gridY / gridHeight) * 100 + Math.random() * 4 - 2}%`;
const size = Math.random() * 15 + 5;
particle.style.width = `${size}px`;
particle.style.height = `${size}px`;
particle.style.color = color;
particle.style.pointerEvents = 'none';
particle.style.animationDuration = `${Math.random() * 1 + 0.5}s`;
particle.style.zIndex = 1000;
document.body.appendChild(particle);
// Remove particle after animation duration
setTimeout(() => {
particle.remove();
}, 1000);
particles.push(particle);
}
}
// Render the scene and animate snake & apples
function render() {
const now = Date.now();
// Animate snake: subtle bobbing/rotation effects
snakeMeshes.forEach((mesh, i) => {
const segment = snake[i];
mesh.position.set(segment.x, 0.4, segment.y);
if (gameRunning) {
const time = now * 0.002;
mesh.rotation.y = Math.sin(time + i * 0.3) * 0.1;
mesh.rotation.x = Math.cos(time + i * 0.2) * 0.05;
}
});
// Animate apples: rotation and floating effect on sphere only
appleMeshes.forEach(mesh => {
if (mesh.geometry.parameters.radius === 0.4) {
mesh.rotation.y += 0.02;
mesh.position.y = 0.4 + Math.sin(now * 0.002) * 0.1;
}
});
renderer.render(scene, camera);
}
// Main game loop managed by requestAnimationFrame
function gameLoop(timestamp) {
if (!gameRunning) return;
if (!lastRenderTime) lastRenderTime = timestamp;
const elapsed = (timestamp - lastRenderTime) / 1000;
const interval = 1 / gameSpeed;
if (elapsed >= interval) {
lastRenderTime = timestamp;
update();
}
render();
animationFrameId = requestAnimationFrame(gameLoop);
}
// Start the game loop
function startGame() {
if (gameRunning) return;
gameRunning = true;
lastRenderTime = 0;
startOverlay.classList.add('hidden');
animationFrameId = requestAnimationFrame(gameLoop);
pauseBtn.setAttribute('aria-pressed', 'false');
pauseBtn.textContent = '❚❚';
}
// End the game and show game over overlay
function endGame() {
gameRunning = false;
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
finalScoreEl.textContent = score;
gameOverOverlay.classList.remove('hidden');
pauseBtn.setAttribute('aria-pressed', 'false');
pauseBtn.textContent = '❚❚';
}
// Toggle pause/resume
function togglePause() {
if (!gameRunning) return;
if (animationFrameId) {
// Pause game
cancelAnimationFrame(animationFrameId);
animationFrameId = null;
pauseBtn.textContent = '▶';
pauseBtn.setAttribute('aria-pressed', 'true');
} else {
// Resume game
lastRenderTime = 0;
animationFrameId = requestAnimationFrame(gameLoop);
pauseBtn.textContent = '❚❚';
pauseBtn.setAttribute('aria-pressed', 'false');
}
}
// Handle touch start for swipe detection
function handleTouchStart(e) {
if (e.touches.length !== 1) return;
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
}
// Handle touch move to detect swipe direction
function handleTouchMove(e) {
if (!touchStartX || !touchStartY || !gameRunning) return;
if (e.touches.length !== 1) {
touchStartX = null;
touchStartY = null;
return;
}
const touchEndX = e.touches[0].clientX;
const touchEndY = e.touches[0].clientY;
const diffX = touchStartX - touchEndX;
const diffY = touchStartY - touchEndY;
// Only trigger if significant swipe (to prevent accidental small moves)
const threshold = 30;
if (Math.abs(diffX) < threshold && Math.abs(diffY) < threshold) {
return;
}
if (Math.abs(diffX) > Math.abs(diffY)) {
// Horizontal swipe
nextDirection = diffX > 0 ? 'left' : 'right';
} else {
// Vertical swipe
nextDirection = diffY > 0 ? 'up' : 'down';
}
// Reset to prevent multiple triggers
touchStartX = null;
touchStartY = null;
}
// Background ambient particles on body (unchanged)
function createBackgroundParticles() {
for (let i = 0; i < 80; i++) {
const particle = document.createElement('div');
particle.className = 'particle';
particle.style.left = `${Math.random() * 100}%`;
particle.style.top = `${Math.random() * 100}%`;
const size = Math.random() * 10 + 3;
particle.style.width = `${size}px`;
particle.style.height = `${size}px`;
particle.style.color = getRandomColor();
particle.style.animationDuration = `${Math.random() * 10 + 5}s`;
particle.style.animationDelay = `${Math.random() * 5}s`;
document.body.appendChild(particle);
}
for (let i = 0; i < 5; i++) {
const glow = document.createElement('div');
glow.className = 'glow';
glow.style.left = `${Math.random() * 100}%`;
glow.style.top = `${Math.random() * 100}%`;
const size = Math.random() * 300 + 100;
glow.style.width = `${size}px`;
glow.style.height = `${size}px`;
glow.style.background = `radial-gradient(circle, ${getRandomColor()} 0%, transparent 70%)`;
document.body.appendChild(glow);
}
}
// Keyboard input handler
function handleKeyDown(e) {
if (!gameRunning) return;
switch (e.key) {
case 'ArrowUp':
case 'w':
case 'W':
nextDirection = 'up';
break;
case 'ArrowDown':
case 's':
case 'S':
nextDirection = 'down';
break;
case 'ArrowLeft':
case 'a':
case 'A':
nextDirection = 'left';
break;
case 'ArrowRight':
case 'd':
case 'D':
nextDirection = 'right';
break;
case ' ':
case 'Pause':
togglePause();
e.preventDefault();
break;
default:
break;
}
}
function addEventListeners() {
startBtn.addEventListener('click', () => {
startGame();
startBtn.blur();
});
restartBtn.addEventListener('click', () => {
initGame();
startGame();
restartBtn.blur();
});
pauseBtn.addEventListener('click', () => {
togglePause();
pauseBtn.blur();
});
window.addEventListener('resize', onWindowResize);
document.addEventListener('keydown', handleKeyDown);
const gameBoard = document.querySelector('.game-board');
gameBoard.addEventListener('touchstart', handleTouchStart, { passive: true });
gameBoard.addEventListener('touchmove', handleTouchMove, { passive: true });
}
// Initialize everything on load
function init() {
initThreeScene();
initGame();
createBackgroundParticles();
addEventListeners();
// Ensure 3D canvas fills container on start
onWindowResize();
}
window.addEventListener('load', init);
})();
</script>
</body>
</html>
aria-pressed state toggle.passive: true for touch listeners for performance.Would you like me to help with further optimizations (e.g. adding TypeScript, external JS modules, or even more advanced game logic)?
Certainly! Acting as a senior software engineer, the goal here is to elevate your existing 3D Snake Adventure game by improving code architecture, performance, scalability, and maintainability, while additionally enhancing UX, responsiveness, and applying modern JS best practices.
Below are the key areas to improve and how I will approach them with corresponding upgrade strategies:
Encapsulate game logic into maintainable, testable classes:
Vector2 utility usage to handle positions cleanly.Snake class to manage snake state and movement.AppleManager class to handle apple spawning and management.Game class for overall flow, input, and rendering.This separation isolates responsibilities, reduces global state, and improves extensibility (e.g. easier to add power-ups, levels).
const/let appropriately.(Will deliver a fully modular, clean approach with class-based JS ES6+ style inside a single HTML file.)
Vector2 class: Clean 2D coordinate management with utility methods.Snake class: Handles movement, direction enforcement, collision detection efficiently with internal state.AppleManager class: Handles randomized spawning avoiding collisions and color assignment.Game class: Handles Three.js initialization, rendering, user input (keyboard/touch), timing logic with fixed timestep, separation of concerns.Snake, AppleManager).If you want, I can help implement any of these next steps or further polish the UX/UI visuals. This refactor is designed for you to scale the game logic easily and maintain a performant, readable codebase.
Would you like me to:
Let me know!
Not yet included in a published release.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Epic 3D Snake Adventure - Refactored</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js" defer></script>
<style>
/* Keep your existing CSS and tweak if needed. For brevity, just a minimal reset and container here */
body, html {
margin: 0; padding: 0; overflow: hidden; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: radial-gradient(circle at center, #0f0c29, #302b63, #24243e);
color: white;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
#app {
width: 100%;
max-width: 800px;
height: 80vh;
position: relative;
user-select: none;
outline: none;
}
/* Additional styles kept as before or simplified for this example */
/* Could add improvements for buttons, overlay, etc. */
</style>
</head>
<body>
<div id="app" tabindex="0" role="application" aria-label="3D Snake Adventure game area"></div>
<script type="module">
// Using ES Modules syntax, so defer attribute must be present on script tag.
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.128/build/three.module.js';
/**
* 2D Vector Utility to Handle Positions Cleanly
*/
class Vector2 {
constructor(x, y) {
this.x = x; this.y = y;
}
equals(vec) {
return this.x === vec.x && this.y === vec.y;
}
clone() {
return new Vector2(this.x, this.y);
}
}
/**
* Manages the snake body and movement logic
*/
class Snake {
/**
* @param {number} gridWidth
* @param {number} gridHeight
*/
constructor(gridWidth, gridHeight) {
this.gridWidth = gridWidth;
this.gridHeight = gridHeight;
this.direction = 'right';
this.nextDirection = 'right';
this.body = [];
this.growSegments = 0;
this.reset();
}
reset() {
this.body = [
new Vector2(Math.floor(this.gridWidth / 2), Math.floor(this.gridHeight / 2)),
new Vector2(Math.floor(this.gridWidth / 2) - 1, Math.floor(this.gridHeight / 2)),
new Vector2(Math.floor(this.gridWidth / 2) - 2, Math.floor(this.gridHeight / 2)),
];
this.direction = 'right';
this.nextDirection = 'right';
this.growSegments = 0;
}
setDirection(newDir) {
// Prevent 180-degree turns
const opposites = {
up: 'down',
down: 'up',
left: 'right',
right: 'left',
};
if (newDir && newDir !== opposites[this.direction]) {
this.nextDirection = newDir;
}
}
move() {
// Apply next direction (validated)
this.direction = this.nextDirection;
// Calculate new head position
const head = this.body[0].clone();
switch(this.direction) {
case 'up': head.y--; break;
case 'down': head.y++; break;
case 'left': head.x--; break;
case 'right': head.x++; break;
}
// Wrap around edges
head.x = (head.x + this.gridWidth) % this.gridWidth;
head.y = (head.y + this.gridHeight) % this.gridHeight;
// Check self collision
if (this.body.some(segment => segment.equals(head))) {
return false; // Collided with itself
}
// Add new head
this.body.unshift(head);
// Handle growth or normal tail removal
if (this.growSegments > 0) {
this.growSegments--;
} else {
this.body.pop();
}
return true; // Successful move
}
grow(segments = 1) {
this.growSegments += segments;
}
}
/**
* Manages apple spawning and appearance
*/
class AppleManager {
constructor(gridWidth, gridHeight, snake) {
this.gridWidth = gridWidth;
this.gridHeight = gridHeight;
this.snake = snake; // Reference to snake to avoid collisions
this.minApples = 3;
this.maxApples = 5;
this.apples = [];
}
reset() {
this.apples = [];
this.spawnApples();
}
isOccupied(x, y) {
// Check if snake or apple occupies this position
return this.snake.body.some(s => s.x === x && s.y === y) ||
this.apples.some(a => a.position.x === x && a.position.y === y);
}
spawnApples() {
const targetCount = Math.floor(Math.random() * (this.maxApples - this.minApples + 1)) + this.minApples;
while (this.apples.length < targetCount) {
const x = Math.floor(Math.random() * this.gridWidth);
const y = Math.floor(Math.random() * this.gridHeight);
if (!this.isOccupied(x, y)) {
this.apples.push({
position: new Vector2(x, y),
color: AppleManager.getRandomColor()
});
}
}
}
removeAppleAt(x, y) {
const idx = this.apples.findIndex(a => a.position.x === x && a.position.y === y);
if (idx !== -1) {
const [removed] = this.apples.splice(idx, 1);
return removed;
}
return null;
}
static getRandomColor() {
const colors = [
'#FF5252', '#FF4081', '#E040FB', '#7C4DFF',
'#536DFE', '#448AFF', '#40C4FF', '#18FFFF',
'#64FFDA', '#69F0AE', '#B2FF59', '#EEFF41'
];
return colors[Math.floor(Math.random() * colors.length)];
}
}
/**
* Controls the entire game flow
*/
class Game {
constructor(container) {
this.container = container;
// Grid size
this.gridWidth = 20;
this.gridHeight = 15;
// Game state
this.score = 0;
this.applesEaten = 0;
this.gameSpeed = 8; // moves per second
this.running = false;
this.paused = false;
// Time management for fixed step update
this.accumulatedTime = 0;
this.stepInterval = 1000 / this.gameSpeed;
// Three.js setup
this.initThree();
// Game objects
this.snake = new Snake(this.gridWidth, this.gridHeight);
this.appleManager = new AppleManager(this.gridWidth, this.gridHeight, this.snake);
// Store meshes for updating efficiently
this.snakeMeshes = [];
this.appleMeshes = [];
// Bind methods to this context
this.animate = this.animate.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleTouchStart = this.handleTouchStart.bind(this);
this.handleTouchMove = this.handleTouchMove.bind(this);
this.touchStart = null;
this.setupInput();
this.initUI();
this.reset();
}
initThree() {
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0x0a0a1f);
this.scene.fog = new THREE.Fog(0x0a0a1f, 15, 50);
const width = this.container.clientWidth;
const height = this.container.clientHeight;
this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
this.camera.position.set(this.gridWidth / 2, this.gridHeight * 1.5, this.gridHeight * 2);
this.camera.lookAt(this.gridWidth / 2, 0, this.gridHeight / 2);
this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
this.renderer.setSize(width, height);
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
this.container.appendChild(this.renderer.domElement);
this.setupLights();
this.setupFloorAndGrid();
window.addEventListener('resize', () => this.resize());
}
setupLights() {
this.scene.add(new THREE.AmbientLight(0xffffff, 0.4));
const dirLight = new THREE.DirectionalLight(0xffffff, 0.8);
dirLight.position.set(this.gridWidth / 2, this.gridHeight * 2, this.gridHeight / 2);
dirLight.castShadow = true;
dirLight.shadow.mapSize.width = 1024;
dirLight.shadow.mapSize.height = 1024;
this.scene.add(dirLight);
}
setupFloorAndGrid() {
const groundGeometry = new THREE.PlaneGeometry(this.gridWidth * 1.2, this.gridHeight * 1.2);
const groundMaterial = new THREE.MeshPhongMaterial({
color: 0x1a1a2e,
shininess: 30,
side: THREE.DoubleSide,
emissive: 0x121230,
emissiveIntensity: 0.2
});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.set(this.gridWidth / 2, -0.5, this.gridHeight / 2);
ground.receiveShadow = true;
this.scene.add(ground);
const gridHelper = new THREE.GridHelper(
Math.max(this.gridWidth, this.gridHeight) * 1.2,
Math.max(this.gridWidth, this.gridHeight),
0x444466,
0x222244
);
gridHelper.position.set(this.gridWidth / 2, 0.01, this.gridHeight / 2);
gridHelper.material.opacity = 0.3;
gridHelper.material.transparent = true;
this.scene.add(gridHelper);
}
resize() {
const width = this.container.clientWidth;
const height = this.container.clientHeight;
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(width, height);
}
setupInput() {
this.container.addEventListener('keydown', this.handleKeyDown);
this.container.addEventListener('touchstart', this.handleTouchStart, { passive: true });
this.container.addEventListener('touchmove', this.handleTouchMove, { passive: true });
this.container.setAttribute('tabindex', '0');
this.container.focus();
// Optional pause on Space using window for now
window.addEventListener('keydown', e => {
if (e.code === 'Space') {
e.preventDefault();
this.togglePause();
}
});
}
initUI() {
// Create overlay & scores dynamically for maintainability
this.ui = {};
// Score display
const scoreContainer = document.createElement('div');
scoreContainer.className = 'score-container';
scoreContainer.style.position = 'absolute';
scoreContainer.style.top = '10px';
scoreContainer.style.left = '50%';
scoreContainer.style.transform = 'translateX(-50%)';
scoreContainer.style.display = 'flex';
scoreContainer.style.gap = '30px';
scoreContainer.style.zIndex = '10';
// Score box helper function
function createScoreBox(label) {
const box = document.createElement('div');
box.className = 'score-box';
box.style.background = 'rgba(0,0,0,0.3)';
box.style.padding = '12px 25px';
box.style.borderRadius = '15px';
box.style.color = 'white';
const h2 = document.createElement('h2');
h2.textContent = label;
box.appendChild(h2);
const p = document.createElement('p');
p.textContent = '0';
box.appendChild(p);
return { box, valueEl: p };
}
const scoreBox = createScoreBox('SCORE');
const applesBox = createScoreBox('APPLES');
scoreContainer.appendChild(scoreBox.box);
scoreContainer.appendChild(applesBox.box);
this.container.appendChild(scoreContainer);
this.ui.scoreEl = scoreBox.valueEl;
this.ui.applesEl = applesBox.valueEl;
// Overlays: Start and Game Over
this.ui.startOverlay = this.createOverlay('3D SNAKE ADVENTURE',
'Swipe or use arrow keys to move the snake. Eat colorful apples to grow. Snake wraps around walls. 3-5 apples at a time.',
'START GAME',
() => this.start()
);
this.ui.gameOverOverlay = this.createOverlay('GAME OVER',
'', // score shown dynamically
'PLAY AGAIN',
() => this.restart(),
true
);
this.container.appendChild(this.ui.startOverlay.overlay);
this.container.appendChild(this.ui.gameOverOverlay.overlay);
this.ui.finalScoreEl = document.createElement('span');
this.ui.gameOverOverlay.overlay.querySelector('p').appendChild(this.ui.finalScoreEl);
}
createOverlay(titleText, descriptionText, buttonText, onClick, initiallyHidden = false) {
const overlay = document.createElement('div');
overlay.className = 'overlay';
if (initiallyHidden) overlay.classList.add('hidden');
overlay.style.position = 'absolute';
overlay.style.top = 0;
overlay.style.left = 0;
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.background = 'rgba(0,0,0,0.9)';
overlay.style.display = 'flex';
overlay.style.flexDirection = 'column';
overlay.style.justifyContent = 'center';
overlay.style.alignItems = 'center';
overlay.style.zIndex = '20';
overlay.style.color = '#f64f59';
overlay.style.textAlign = 'center';
overlay.style.fontWeight = '700';
overlay.style.padding = '20px';
overlay.style.borderRadius = '18px';
overlay.style.backdropFilter = 'blur(10px)';
const h2 = document.createElement('h2');
h2.textContent = titleText;
h2.style.fontSize = '3.5rem';
h2.style.marginBottom = '20px';
h2.style.textShadow = '0 0 15px rgba(246, 79, 89, 0.8)';
overlay.appendChild(h2);
const p = document.createElement('p');
p.textContent = descriptionText;
p.style.maxWidth = '80%';
p.style.fontSize = '1.4rem';
p.style.marginBottom = '20px';
p.style.lineHeight = '1.6';
p.style.color = '#c471ed';
overlay.appendChild(p);
const btn = document.createElement('button');
btn.textContent = buttonText;
btn.style.background = 'linear-gradient(to right, #12c2e9, #c471ed, #f64f59)';
btn.style.border = 'none';
btn.style.padding = '16px 48px';
btn.style.borderRadius = '32px';
btn.style.color = 'white';
btn.style.fontSize = '1.3rem';
btn.style.fontWeight = '700';
btn.style.cursor = 'pointer';
btn.style.boxShadow = '0 6px 20px rgba(0,0,0,0.4), 0 0 15px rgba(200,200,255,0.6)';
btn.style.transition = 'all 0.3s ease';
btn.style.letterSpacing = '1px';
btn.style.position = 'relative';
btn.style.overflow = 'hidden';
btn.style.zIndex = '2';
btn.addEventListener('click', () => {
onClick();
btn.blur();
});
overlay.appendChild(btn);
return { overlay, btn };
}
reset() {
this.score = 0;
this.applesEaten = 0;
this.gameSpeed = 8;
this.running = false;
this.paused = false;
this.stepInterval = 1000 / this.gameSpeed;
this.accumulatedTime = 0;
this.snake.reset();
this.appleManager.reset();
this.clearMeshes();
this.createMeshes();
this.updateUI();
this.ui.startOverlay.overlay.classList.remove('hidden');
this.ui.gameOverOverlay.overlay.classList.add('hidden');
}
clearMeshes() {
this.snakeMeshes.forEach(m => this.scene.remove(m));
this.appleMeshes.forEach(m => this.scene.remove(m));
this.snakeMeshes = [];
this.appleMeshes = [];
}
createMeshes() {
// Snake meshes
this.snakeMeshes = this.snake.body.map((segment, idx) => this.createSnakeMesh(segment, idx === 0));
this.snakeMeshes.forEach(mesh => this.scene.add(mesh));
// Apples meshes
this.appleMeshes = this.appleManager.apples.flatMap(apple => {
const meshes = [];
const appGeom = new THREE.SphereGeometry(0.4, 16, 16);
const material = new THREE.MeshPhongMaterial({
color: apple.color,
shininess: 100,
emissive: new THREE.Color(apple.color),
emissiveIntensity: 0.2,
});
const appMesh = new THREE.Mesh(appGeom, material);
appMesh.position.set(apple.position.x, 0.4, apple.position.y);
appMesh.castShadow = true;
appMesh.receiveShadow = true;
meshes.push(appMesh);
const glowGeom = new THREE.SphereGeometry(0.5, 16, 16);
const glowMat = new THREE.MeshBasicMaterial({
color: apple.color,
transparent: true,
opacity: 0.3,
side: THREE.BackSide,
});
const glowMesh = new THREE.Mesh(glowGeom, glowMat);
glowMesh.position.copy(appMesh.position);
meshes.push(glowMesh);
return meshes;
});
this.appleMeshes.forEach(mesh => this.scene.add(mesh));
}
createSnakeMesh(segment, isHead) {
const size = isHead ? 0.8 : 0.7;
const geometry = new THREE.SphereGeometry(size, 16, 16);
let color;
if (isHead) {
color = new THREE.Color(0x4caf50);
} else {
color = new THREE.Color().setHSL(0.33, 0.7, 0.5);
}
const material = new THREE.MeshPhongMaterial({
color: color,
shininess: 50,
emissive: color,
emissiveIntensity: 0.1,
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(segment.x, 0.4, segment.y);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
updateUI() {
this.ui.scoreEl.textContent = this.score;
this.ui.applesEl.textContent = this.applesEaten;
}
start() {
if (this.running) return;
this.running = true;
this.paused = false;
this.ui.startOverlay.overlay.classList.add('hidden');
this.ui.gameOverOverlay.overlay.classList.add('hidden');
this.animate(performance.now());
}
restart() {
this.reset();
this.start();
}
togglePause() {
if (!this.running) return;
this.paused = !this.paused;
if (!this.paused) {
this.accumulatedTime = 0; // Reset so no catch up rush
this.animate(performance.now());
}
}
// Game logic update step — fixed timestep recommended
update() {
if (!this.running || this.paused) return;
const moved = this.snake.move();
if (!moved) {
this.gameOver();
return;
}
// Check for apple collision
const head = this.snake.body[0];
const apple = this.appleManager.removeAppleAt(head.x, head.y);
if (apple) {
this.snake.grow(1);
this.score += 10;
this.applesEaten++;
this.gameSpeed = Math.min(20, this.gameSpeed + 0.3);
this.stepInterval = 1000 / this.gameSpeed;
this.appleManager.spawnApples();
this.createMeshes(); // recreate apples + snake meshes
this.createParticles(head.x, head.y, apple.color);
this.updateUI();
} else {
this.updateSnakeMeshes();
}
}
updateSnakeMeshes() {
// Move existing snake meshes without re-creating geometry
this.snake.body.forEach((segment, idx) => {
if (!this.snakeMeshes[idx]) {
// Normally shouldn't happen
const mesh = this.createSnakeMesh(segment, idx === 0);
this.snakeMeshes[idx] = mesh;
this.scene.add(mesh);
}
this.snakeMeshes[idx].position.set(segment.x, 0.4, segment.y);
});
// Remove excess meshes if snake shrank (unlikely here but just in case)
if (this.snakeMeshes.length > this.snake.body.length) {
for (let i = this.snake.body.length; i < this.snakeMeshes.length; i++) {
this.scene.remove(this.snakeMeshes[i]);
}
this.snakeMeshes.length = this.snake.body.length;
}
}
createParticles(gridX, gridY, color) {
const rect = this.container.getBoundingClientRect();
const numParticles = 25;
for (let i = 0; i < numParticles; i++) {
const particle = document.createElement('div');
particle.className = 'particle';
particle.style.position = 'absolute';
particle.style.left = `${(gridX / this.gridWidth) * 100 + (Math.random() * 6 - 3)}%`;
particle.style.top = `${(gridY / this.gridHeight) * 100 + (Math.random() * 6 - 3)}%`;
const size = Math.random() * 12 + 6;
particle.style.width = `${size}px`;
particle.style.height = `${size}px`;
particle.style.color = color;
particle.style.pointerEvents = 'none';
particle.style.animationDuration = `${Math.random() * 1 + 0.5}s`;
particle.style.zIndex = '1000';
document.body.appendChild(particle);
setTimeout(() => particle.remove(), 1100);
}
}
animate(time) {
if (!this.running || this.paused) return;
if (!this.lastTime) this.lastTime = time;
const delta = time - this.lastTime;
this.lastTime = time;
this.accumulatedTime += delta;
while (this.accumulatedTime >= this.stepInterval) {
this.update();
this.accumulatedTime -= this.stepInterval;
}
this.animateMeshAnimations();
this.renderer.render(this.scene, this.camera);
this.animationFrameId = requestAnimationFrame(this.animate);
}
animateMeshAnimations() {
const now = Date.now();
// Snake subtle bob and rotation
this.snakeMeshes.forEach((mesh, idx) => {
const segment = this.snake.body[idx];
mesh.position.set(segment.x, 0.4, segment.y);
const time = now * 0.002;
mesh.rotation.y = Math.sin(time + idx * 0.3) * 0.1;
mesh.rotation.x = Math.cos(time + idx * 0.2) * 0.05;
});
// Apple rotation and float
this.appleMeshes.forEach(mesh => {
if (mesh.geometry.parameters.radius === 0.4) {
mesh.rotation.y += 0.02;
mesh.position.y = 0.4 + Math.sin(Date.now() * 0.002) * 0.1;
}
});
}
gameOver() {
this.running = false;
this.ui.gameOverOverlay.overlay.classList.remove('hidden');
this.ui.finalScoreEl.textContent = this.score;
}
// Input event handlers
handleKeyDown(event) {
const keyDirMap = {
ArrowUp: 'up',
ArrowDown: 'down',
ArrowLeft: 'left',
ArrowRight: 'right',
w: 'up',
s: 'down',
a: 'left',
d: 'right',
};
const dir = keyDirMap[event.key];
if (dir) {
this.snake.setDirection(dir);
event.preventDefault();
}
}
handleTouchStart(event) {
if (event.touches.length !== 1) return;
const touch = event.touches[0];
this.touchStart = { x: touch.clientX, y: touch.clientY };
}
handleTouchMove(event) {
if (!this.touchStart || event.touches.length !== 1) return;
const touch = event.touches[0];
const deltaX = this.touchStart.x - touch.clientX;
const deltaY = this.touchStart.y - touch.clientY;
const threshold = 30; // px swipe must pass to count
if (Math.abs(deltaX) < threshold && Math.abs(deltaY) < threshold) return;
if (Math.abs(deltaX) > Math.abs(deltaY)) {
this.snake.setDirection(deltaX > 0 ? 'left' : 'right');
} else {
this.snake.setDirection(deltaY > 0 ? 'up' : 'down');
}
this.touchStart = null;
}
}
// Initialize Game on DOM ready and Three.js load
function init() {
const container = document.getElementById('app');
if (!container) throw new Error('Game container missing');
const game = new Game(container);
}
window.addEventListener('DOMContentLoaded', init);
</script>
<style>
/* Minimal extra overlays styles for demonstration */
.overlay {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.hidden {
display: none !important;
}
/* Same particle and other animations as in your original CSS */
.particle {
position: absolute;
border-radius: 50%;
background: currentColor;
pointer-events: none;
opacity: 0.9;
animation: float 1s ease forwards;
box-shadow: 0 0 8px currentColor;
}
@keyframes float {
from {
transform: translateY(0) translateX(0) scale(1);
opacity: 1;
}
to {
transform: translateY(-100px) translateX(30px) scale(1.5);
opacity: 0;
}
}
</style>
</body>
</html>