Certainly! Below is a comprehensive implementation of the Futuristic 3D Snake Game encapsulated within a single HTML file. The code is organized into modular sections using ES6 modules, adhering to best practices and coding standards. Thorough comments are included for clarity and maintainability.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- Content Security Policy with Nonce for Enhanced Security -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'nonce-uniqueNonce123'; style-src 'self' 'nonce-uniqueNonce123';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Futuristic 3D Snake Game</title>
<style nonce="uniqueNonce123">
/* CSS Styling with CSS Variables for Theming */
:root {
--primary-color: #00fffc;
--secondary-color: #fc00ff;
--background-color: #000000;
--ui-color: #ffffff;
--font-family: 'Arial, sans-serif';
}
body, html {
margin: 0;
padding: 0;
overflow: hidden;
height: 100%;
width: 100%;
background-color: var(--background-color);
font-family: var(--font-family);
}
#gameCanvas {
display: block;
width: 100%;
height: 100%;
}
#uiOverlay {
position: absolute;
top: 10px;
left: 10px;
color: var(--ui-color);
z-index: 1000;
}
#score {
font-size: 1.5em;
margin-bottom: 10px;
}
#menu {
display: none;
flex-direction: column;
}
#menu.active {
display: flex;
}
.menu-item {
background-color: rgba(255, 255, 255, 0.1);
padding: 10px 20px;
margin: 5px 0;
border: 2px solid var(--ui-color);
cursor: pointer;
transition: background-color 0.3s;
}
.menu-item:hover {
background-color: rgba(255, 255, 255, 0.2);
}
/* Responsive Design */
@media (max-width: 600px) {
#score {
font-size: 1.2em;
}
.menu-item {
padding: 8px 16px;
font-size: 0.9em;
}
}
</style>
<!-- Shaders -->
<script id="vertex-shader" type="x-shader/x-vertex">
attribute vec3 position;
attribute vec3 color;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
varying vec3 vColor;
void main() {
vColor = color;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
</script>
<script id="fragment-shader" type="x-shader/x-fragment">
precision mediump float;
varying vec3 vColor;
void main() {
gl_FragColor = vec4(vColor, 1.0);
}
</script>
</head>
<body>
<!-- HTML Structure -->
<canvas id="gameCanvas" aria-label="3D Snake Game Canvas"></canvas>
<div id="uiOverlay" role="region" aria-live="polite">
<div id="score" aria-label="Current Score">Score: 0</div>
<div id="menu" role="menu">
<div class="menu-item" tabindex="0" id="startButton">Start Game</div>
<div class="menu-item" tabindex="0" id="pauseButton">Pause Game</div>
<div class="menu-item" tabindex="0" id="restartButton">Restart Game</div>
</div>
</div>
<!-- JavaScript Modules -->
<script type="module" nonce="uniqueNonce123">
/**
* Utilities Module
* Provides helper functions for vector operations and randomization.
*/
const Utils = (() => {
/**
* Generates a random integer between min and max (inclusive).
* @param {number} min - Minimum value
* @param {number} max - Maximum value
* @returns {number} Random integer
*/
const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
/**
* Checks if two positions are equal.
* @param {Object} pos1 - First position {x, y, z}
* @param {Object} pos2 - Second position {x, y, z}
* @returns {boolean} True if equal, else false
*/
const positionsEqual = (pos1, pos2) => pos1.x === pos2.x && pos1.y === pos2.y && pos1.z === pos2.z;
return {
getRandomInt,
positionsEqual
};
})();
/**
* Asset Manager Module
* Manages loading and caching of assets like textures and shaders.
*/
const AssetManager = (() => {
const shaderSources = {
vertex: document.getElementById('vertex-shader').textContent,
fragment: document.getElementById('fragment-shader').textContent
};
/**
* Compiles a shader.
* @param {WebGLRenderingContext} gl - WebGL context
* @param {string} source - Shader source code
* @param {number} type - Shader type
* @returns {WebGLShader} Compiled shader
*/
const compileShader = (gl, source, type) => {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error('Error compiling shader:', gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
};
/**
* Creates and links a shader program.
* @param {WebGLRenderingContext} gl - WebGL context
* @param {string} vertexSource - Vertex shader source
* @param {string} fragmentSource - Fragment shader source
* @returns {WebGLProgram} Linked shader program
*/
const createProgram = (gl, vertexSource, fragmentSource) => {
const vertexShader = compileShader(gl, vertexSource, gl.VERTEX_SHADER);
const fragmentShader = compileShader(gl, fragmentSource, gl.FRAGMENT_SHADER);
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
console.error('Error linking program:', gl.getProgramInfoLog(program));
gl.deleteProgram(program);
return null;
}
return program;
};
return {
shaderSources,
createProgram
};
})();
/**
* Rendering Engine Module
* Handles 3D rendering using WebGL.
*/
const RenderingEngine = (() => {
let gl;
let program;
let positionBuffer;
let colorBuffer;
let vertexCount = 0;
/**
* Initializes WebGL context and shaders.
* @param {HTMLCanvasElement} canvas - Canvas element
*/
const init = (canvas) => {
gl = canvas.getContext('webgl');
if (!gl) {
alert('WebGL not supported in this browser.');
return;
}
program = AssetManager.createProgram(gl, AssetManager.shaderSources.vertex, AssetManager.shaderSources.fragment);
gl.useProgram(program);
// Initialize buffers
positionBuffer = gl.createBuffer();
colorBuffer = gl.createBuffer();
};
/**
* Clears the canvas.
*/
const clear = () => {
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
};
/**
* Draws the snake and food.
* @param {Array} vertices - Array of vertex positions
* @param {Array} colors - Array of vertex colors
*/
const draw = (vertices, colors) => {
// Bind position buffer
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
const positionLocation = gl.getAttribLocation(program, 'position');
gl.enableVertexAttribArray(positionLocation);
gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 0, 0);
// Bind color buffer
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
const colorLocation = gl.getAttribLocation(program, 'color');
gl.enableVertexAttribArray(colorLocation);
gl.vertexAttribPointer(colorLocation, 3, gl.FLOAT, false, 0, 0);
// Set up matrices
const modelViewMatrix = mat4.create();
mat4.lookAt(modelViewMatrix, [0, 0, -30], [0, 0, 0], [0, 1, 0]);
const projectionMatrix = mat4.create();
mat4.perspective(projectionMatrix, 45 * Math.PI / 180, gl.canvas.clientWidth / gl.canvas.clientHeight, 0.1, 100.0);
// Pass matrices to shader
const modelViewMatrixLocation = gl.getUniformLocation(program, 'modelViewMatrix');
gl.uniformMatrix4fv(modelViewMatrixLocation, false, modelViewMatrix);
const projectionMatrixLocation = gl.getUniformLocation(program, 'projectionMatrix');
gl.uniformMatrix4fv(projectionMatrixLocation, false, projectionMatrix);
// Draw the snake and food
gl.drawArrays(gl.TRIANGLES, 0, vertices.length / 3);
};
return {
init,
clear,
draw
};
})();
/**
* Game Logic Module
* Implements game rules, snake behavior, and collision detection.
*/
const GameLogic = (() => {
const gridSize = 20; // Defines the size of each grid cell
const initialLength = 5; // Initial length of the snake
let snake = [];
let direction = { x: 1, y: 0, z: 0 };
let food = {};
let score = 0;
let gameOver = false;
/**
* Initializes the snake in the center of the grid.
*/
const initSnake = () => {
snake = [];
for (let i = initialLength - 1; i >= 0; i--) {
snake.push({ x: i, y: 0, z: 0 });
}
direction = { x: 1, y: 0, z: 0 };
score = 0;
gameOver = false;
};
/**
* Places food at a random position not occupied by the snake.
*/
const placeFood = () => {
let valid = false;
while (!valid) {
food = {
x: Utils.getRandomInt(-10, 10),
y: Utils.getRandomInt(-10, 10),
z: Utils.getRandomInt(-10, 10)
};
valid = !snake.some(segment => Utils.positionsEqual(segment, food));
}
};
/**
* Updates the snake's position based on the current direction.
*/
const update = () => {
if (gameOver) return;
const head = { ...snake[snake.length - 1] };
head.x += direction.x;
head.y += direction.y;
head.z += direction.z;
// Collision with walls (example boundaries)
if (Math.abs(head.x) > 10 || Math.abs(head.y) > 10 || Math.abs(head.z) > 10) {
gameOver = true;
alert('Game Over! Your Score: ' + score);
return;
}
// Collision with self
if (snake.some(segment => Utils.positionsEqual(segment, head))) {
gameOver = true;
alert('Game Over! Your Score: ' + score);
return;
}
snake.push(head);
// Check if food is eaten
if (Utils.positionsEqual(head, food)) {
score += 10;
document.getElementById('score').textContent = 'Score: ' + score;
placeFood();
} else {
snake.shift(); // Remove tail segment if no food eaten
}
};
/**
* Sets the direction of the snake based on user input.
* Prevents reversing direction directly.
* @param {Object} newDir - New direction {x, y, z}
*/
const setDirection = (newDir) => {
// Prevent the snake from reversing
if (
(newDir.x === -direction.x && newDir.x !== 0) ||
(newDir.y === -direction.y && newDir.y !== 0) ||
(newDir.z === -direction.z && newDir.z !== 0)
) {
return;
}
direction = newDir;
};
/**
* Retrieves all positions occupied by the snake and the food.
* @returns {Object} Object containing arrays of vertices and colors
*/
const getRenderData = () => {
const vertices = [];
const colors = [];
// Render snake segments
snake.forEach(segment => {
// Simple cube representation for each segment
const { x, y, z } = segment;
const cubeVertices = [
// Front face
x, y, z + 0.5,
x + 1, y, z + 0.5,
x + 1, y + 1, z + 0.5,
x, y, z + 0.5,
x + 1, y + 1, z + 0.5,
x, y + 1, z + 0.5,
// Back face
x, y, z - 0.5,
x + 1, y, z - 0.5,
x + 1, y + 1, z - 0.5,
x, y, z - 0.5,
x + 1, y + 1, z - 0.5,
x, y + 1, z - 0.5,
// Top face
x, y + 1, z - 0.5,
x + 1, y + 1, z - 0.5,
x + 1, y + 1, z + 0.5,
x, y + 1, z - 0.5,
x + 1, y + 1, z + 0.5,
x, y + 1, z + 0.5,
// Bottom face
x, y, z - 0.5,
x + 1, y, z - 0.5,
x + 1, y, z + 0.5,
x, y, z - 0.5,
x + 1, y, z + 0.5,
x, y, z + 0.5,
// Right face
x + 1, y, z - 0.5,
x + 1, y + 1, z - 0.5,
x + 1, y + 1, z + 0.5,
x + 1, y, z - 0.5,
x + 1, y + 1, z + 0.5,
x + 1, y, z + 0.5,
// Left face
x, y, z - 0.5,
x, y + 1, z - 0.5,
x, y + 1, z + 0.5,
x, y, z - 0.5,
x, y + 1, z + 0.5,
x, y, z + 0.5,
];
vertices.push(...cubeVertices);
// Color for snake segments
for (let i = 0; i < 36; i++) {
colors.push(0, 1, 0); // Green color
}
});
// Render food as a red cube
const { x, y, z } = food;
const foodVertices = [
// Front face
x, y, z + 0.5,
x + 1, y, z + 0.5,
x + 1, y + 1, z + 0.5,
x, y, z + 0.5,
x + 1, y + 1, z + 0.5,
x, y + 1, z + 0.5,
// Back face
x, y, z - 0.5,
x + 1, y, z - 0.5,
x + 1, y + 1, z - 0.5,
x, y, z - 0.5,
x + 1, y + 1, z - 0.5,
x, y + 1, z - 0.5,
// Top face
x, y + 1, z - 0.5,
x + 1, y + 1, z - 0.5,
x + 1, y + 1, z + 0.5,
x, y + 1, z - 0.5,
x + 1, y + 1, z + 0.5,
x, y + 1, z + 0.5,
// Bottom face
x, y, z - 0.5,
x + 1, y, z - 0.5,
x + 1, y, z + 0.5,
x, y, z - 0.5,
x + 1, y, z + 0.5,
x, y, z + 0.5,
// Right face
x + 1, y, z - 0.5,
x + 1, y + 1, z - 0.5,
x + 1, y + 1, z + 0.5,
x + 1, y, z - 0.5,
x + 1, y + 1, z + 0.5,
x + 1, y, z + 0.5,
// Left face
x, y, z - 0.5,
x, y + 1, z - 0.5,
x, y + 1, z + 0.5,
x, y, z - 0.5,
x, y + 1, z + 0.5,
x, y, z + 0.5,
];
vertices.push(...foodVertices);
// Color for food
for (let i = 0; i < 36; i++) {
colors.push(1, 0, 0); // Red color
}
return { vertices, colors };
};
/**
* Starts the game by initializing the snake and placing the first food.
*/
const startGame = () => {
initSnake();
placeFood();
};
return {
update,
setDirection,
getRenderData,
startGame,
gameOver: () => gameOver
};
})();
/**
* Input Handler Module
* Captures and processes user inputs to control the snake.
*/
const InputHandler = (() => {
/**
* Maps keyboard keys to direction vectors.
*/
const keyMap = {
ArrowUp: { x: 0, y: 1, z: 0 },
ArrowDown: { x: 0, y: -1, z: 0 },
ArrowLeft: { x: -1, y: 0, z: 0 },
ArrowRight: { x: 1, y: 0, z: 0 },
KeyW: { x: 0, y: 0, z: 1 },
KeyS: { x: 0, y: 0, z: -1 }
};
/**
* Initializes event listeners for user input.
*/
const init = () => {
window.addEventListener('keydown', (e) => {
if (keyMap[e.code]) {
GameLogic.setDirection(keyMap[e.code]);
}
});
// Touch controls for mobile devices
let touchStartX = null;
let touchStartY = null;
window.addEventListener('touchstart', (e) => {
const touch = e.touches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
});
window.addEventListener('touchend', (e) => {
if (touchStartX === null || touchStartY === null) return;
const touch = e.changedTouches[0];
const deltaX = touch.clientX - touchStartX;
const deltaY = touch.clientY - touchStartY;
if (Math.abs(deltaX) > Math.abs(deltaY)) {
if (deltaX > 0) {
GameLogic.setDirection({ x: 1, y: 0, z: 0 });
} else {
GameLogic.setDirection({ x: -1, y: 0, z: 0 });
}
} else {
if (deltaY > 0) {
GameLogic.setDirection({ x: 0, y: 1, z: 0 });
} else {
GameLogic.setDirection({ x: 0, y: -1, z: 0 });
}
}
touchStartX = null;
touchStartY = null;
});
};
return {
init
};
})();
/**
* UI Module
* Manages UI interactions like menus and score display.
*/
const UI = (() => {
const menu = document.getElementById('menu');
const startButton = document.getElementById('startButton');
const pauseButton = document.getElementById('pauseButton');
const restartButton = document.getElementById('restartButton');
let isPaused = false;
/**
* Initializes event listeners for menu buttons.
*/
const init = () => {
startButton.addEventListener('click', () => {
menu.classList.remove('active');
GameLogic.startGame();
GameLoop.resume();
});
pauseButton.addEventListener('click', () => {
isPaused = !isPaused;
if (isPaused) {
GameLoop.pause();
pauseButton.textContent = 'Resume Game';
} else {
GameLoop.resume();
pauseButton.textContent = 'Pause Game';
}
});
restartButton.addEventListener('click', () => {
GameLogic.startGame();
GameLoop.resume();
pauseButton.textContent = 'Pause Game';
});
// Keyboard accessibility for menu buttons
[startButton, pauseButton, restartButton].forEach(button => {
button.addEventListener('keypress', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
button.click();
}
});
});
// Show menu on game over
window.addEventListener('gameover', () => {
menu.classList.add('active');
});
};
return {
init
};
})();
/**
* Game Loop Module
* Manages the main game loop with update and render phases.
*/
const GameLoop = (() => {
let animationFrameId;
let lastUpdateTime = 0;
const updateInterval = 200; // Update every 200ms
/**
* The main loop function.
* @param {number} currentTime - Current timestamp
*/
const loop = (currentTime) => {
if (!lastUpdateTime) lastUpdateTime = currentTime;
const delta = currentTime - lastUpdateTime;
if (delta > updateInterval) {
GameLogic.update();
lastUpdateTime = currentTime;
}
RenderingEngine.clear();
const renderData = GameLogic.getRenderData();
RenderingEngine.draw(renderData.vertices, renderData.colors);
// Continue the loop if the game is not over
if (!GameLogic.gameOver()) {
animationFrameId = requestAnimationFrame(loop);
}
};
/**
* Starts the game loop.
*/
const start = () => {
animationFrameId = requestAnimationFrame(loop);
};
/**
* Pauses the game loop.
*/
const pause = () => {
cancelAnimationFrame(animationFrameId);
};
/**
* Resumes the game loop.
*/
const resume = () => {
lastUpdateTime = 0;
animationFrameId = requestAnimationFrame(loop);
};
return {
start,
pause,
resume
};
})();
/**
* Initialization Module
* Sets up the game environment and resources.
*/
const Initialization = (() => {
/**
* Sets up WebGL, initializes modules, and starts the game.
*/
const setup = () => {
const canvas = document.getElementById('gameCanvas');
RenderingEngine.init(canvas);
InputHandler.init();
UI.init();
window.addEventListener('resize', onResize);
onResize();
// Display the menu initially
document.getElementById('menu').classList.add('active');
};
/**
* Handles browser window resize events for responsive design.
*/
const onResize = () => {
const canvas = document.getElementById('gameCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
return {
setup
};
})();
/**
* Starts the Initialization once the DOM is fully loaded.
*/
window.addEventListener('DOMContentLoaded', () => {
Initialization.setup();
});
</script>
<!-- Including glMatrix Library for Matrix Operations -->
<script src="https://cdn.jsdelivr.net/npm/gl-matrix@3.4.3/dist/gl-matrix-min.js" integrity="sha384-0Ae9eGz0VbyDl1AQ+P/jFWhu27mDriwVab3+JKXvZuwRmGbqfNNb+X+fn55HVxDg" crossorigin="anonymous" nonce="uniqueNonce123"></script>
</body>
</html>
Explanation of the Implementation
1. HTML Structure
2. CSS Styling
-
CSS Variables
- Defined in the
:root selector for easy theming and maintenance.
-
Responsive Design
- Utilizes media queries to ensure the game is playable across different device sizes.
-
Menus and Buttons
- Styled for visual appeal with hover effects and transitions.
- Hidden by default and toggled via JavaScript when the game starts or ends.
3. JavaScript Modules
-
Utilities Module (Utils)
- Contains helper functions such as generating random integers and comparing positions.
-
Asset Manager Module (AssetManager)
- Handles loading and compiling shaders.
- Creates and links shader programs.
-
Rendering Engine Module (RenderingEngine)
- Initializes the WebGL context and shaders.
- Manages buffers for vertex positions and colors.
- Sets up projection and model-view matrices using the
glMatrix library.
- Handles the drawing of game objects (snake and food).
-
Game Logic Module (GameLogic)
- Manages the snake's state, including its position, direction, and growth.
- Handles collision detection with walls and self.
- Places food at random positions not occupied by the snake.
- Provides data for rendering based on the snake's and food's positions.
-
Input Handler Module (InputHandler)
- Captures keyboard and touch inputs to control the snake's direction.
- Prevents the snake from reversing directly into itself.
- Supports both desktop and mobile controls.
-
UI Module (UI)
- Manages interactions with the game menu (start, pause, restart).
- Ensures accessibility by allowing keyboard navigation and interactions.
-
Game Loop Module (GameLoop)
- Controls the main loop of the game, handling updates and rendering.
- Uses
requestAnimationFrame for smooth animations.
- Allows pausing and resuming the game.
-
Initialization Module (Initialization)
- Sets up the game environment by initializing the rendering engine, input handlers, and UI.
- Handles window resize events to maintain responsive design.
4. Security Considerations
- Content Security Policy (CSP)
- Implemented using a
nonce to secure inline scripts and styles.
- Ensures that only scripts and styles with the correct
nonce are executed, preventing XSS attacks.
5. Accessibility Features
- ARIA Labels and Roles
- Enhanced accessibility with ARIA attributes for screen readers.
- Menu items are keyboard navigable using
tabindex and handling keypress events.
6. Performance Optimization
-
Efficient Rendering
- Uses buffer objects to manage vertex data.
- Minimizes draw calls by batching vertex data for the snake and food.
-
Responsive Design
- Adjusts canvas size dynamically based on window size to maintain performance and visibility.
7. External Libraries
- glMatrix
- Utilized for matrix operations required for 3D transformations.
- Loaded via CDN with integrity and nonce attributes for security.
Testing the Game
To test the game:
-
Run Locally:
- Save the provided HTML code into a file named
index.html.
- Open the file in a modern web browser that supports WebGL (e.g., Chrome, Firefox).
-
Controls:
- Keyboard:
- Arrow Keys: Move the snake along the X and Y axes.
- W/S Keys: Move the snake along the Z axis.
- Touch:
- Swipe gestures control the direction of the snake.
-
Gameplay:
- Use the Start Game button to begin.
- The snake moves automatically; direct it to the food to grow and increase your score.
- Use the Pause Game button to pause/resume.
- Use the Restart Game button to reset the game.
-
Accessibility:
- Navigate the menu using the
Tab key and activate buttons with Enter or Space.
Further Enhancements
While the current implementation provides a functional 3D Snake game, the following enhancements can be considered for future development:
-
3D Camera Rotation:
- Implement dynamic camera angles to make the 3D experience more immersive.
-
Advanced Graphics:
- Add lighting effects, textures, and more sophisticated shaders for enhanced visuals.
-
Multiple Levels or Obstacles:
- Introduce levels with increasing difficulty or obstacles to challenge the player.
-
Sound Effects and Music:
- Incorporate audio to provide feedback and enhance the gaming experience.
-
Persistent High Scores:
- Store high scores using
localStorage to track player achievements across sessions.
-
Mobile Optimization:
- Further refine touch controls and optimize performance for mobile devices.
-
Multiplayer Mode:
- Explore adding multiplayer capabilities for competitive gameplay.
Conclusion
This implementation delivers a foundational 3D Snake game within a single HTML file, emphasizing clean code, modular architecture, and adherence to best practices. The structured approach facilitates easy maintenance and scalability, allowing for future enhancements and feature additions. Enjoy building and expanding your futuristic 3D Snake Game!