Sure! Below is a simple 3D Snake game implemented in HTML, CSS, and JavaScript, all contained in a single file. You can copy and paste this code into a file with a .html extension (e.g., 3d_snake_game.html) and open it in your web browser to play the game.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>3D Snake Game</title>
<style>
body { margin: 0; overflow: hidden; background-color: #000; }
canvas { display: block; }
</style>
</head>
<body>
<script>
// ================================
// Begin of Three.js library
// ================================
// Minified Three.js r128
// (C) 2010-2021 three.js authors
// https://threejs.org/
// For brevity, the minified Three.js code is not included here.
// You can download the minified version from:
// https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js
// and paste it here.
// ================================
// End of Three.js library
// ================================
// Paste the minified Three.js code between the markers above.
// ================================
// Begin of 3D Snake Game Code
// ================================
// Check if WebGL is supported
if ( !window.WebGLRenderingContext ) {
alert("Your browser does not support WebGL. Please try a different browser.");
}
// Set up the scene, camera, and renderer
var scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000);
var camera = new THREE.PerspectiveCamera(
75, window.innerWidth/window.innerHeight, 0.1, 1000
);
camera.position.set(0, 20, 30);
camera.lookAt(0, 0, 0);
var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Lighting
var light = new THREE.DirectionalLight(0xffffff, 0.8);
light.position.set(0, 50, 50);
scene.add(light);
var ambientLight = new THREE.AmbientLight(0xffffff, 0.2);
scene.add(ambientLight);
// Snake variables
var snake = [];
var snakeLength = 5;
var cubeSize = 1;
var direction = new THREE.Vector3(1, 0, 0);
var moveInterval = 200; // milliseconds
var lastMoveTime = 0;
// Food variables
var food;
var foodMaterial = new THREE.MeshLambertMaterial({ color: 0xff0000 });
// Create the snake
function createSnake() {
var snakeMaterial = new THREE.MeshLambertMaterial({ color: 0x00ff00 });
for (var i = 0; i < snakeLength; i++) {
var geometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
var cube = new THREE.Mesh(geometry, snakeMaterial);
cube.position.x = -i * cubeSize;
scene.add(cube);
snake.push(cube);
}
}
// Create the food
function createFood() {
var geometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
food = new THREE.Mesh(geometry, foodMaterial);
resetFoodPosition();
scene.add(food);
}
function resetFoodPosition() {
food.position.x = Math.floor(Math.random() * 20 - 10) * cubeSize;
food.position.y = Math.floor(Math.random() * 10) * cubeSize;
food.position.z = Math.floor(Math.random() * 20 - 10) * cubeSize;
}
// Handle keyboard input
document.addEventListener('keydown', function(event) {
switch(event.key) {
case 'ArrowUp':
if (direction.y !== -1) direction.set(0, 1, 0);
break;
case 'ArrowDown':
if (direction.y !== 1) direction.set(0, -1, 0);
break;
case 'ArrowLeft':
if (direction.x !== 1) direction.set(-1, 0, 0);
break;
case 'ArrowRight':
if (direction.x !== -1) direction.set(1, 0, 0);
break;
case 'w':
if (direction.z !== 1) direction.set(0, 0, -1);
break;
case 's':
if (direction.z !== -1) direction.set(0, 0, 1);
break;
}
});
// Game loop
function animate(time) {
requestAnimationFrame(animate);
if (!lastMoveTime) lastMoveTime = time;
if (time - lastMoveTime > moveInterval) {
moveSnake();
lastMoveTime = time;
}
renderer.render(scene, camera);
}
function moveSnake() {
// Get current head position
var head = snake[0];
var newPosition = new THREE.Vector3().addVectors(head.position, new THREE.Vector3().copy(direction).multiplyScalar(cubeSize));
// Move body
for (var i = snake.length - 1; i > 0; i--) {
snake[i].position.copy(snake[i - 1].position);
}
// Move head
head.position.copy(newPosition);
// Check for collision with food
if (head.position.distanceTo(food.position) < cubeSize / 2) {
growSnake();
resetFoodPosition();
}
// Check for collision with self or boundaries
for (var i = 1; i < snake.length; i++) {
if (head.position.distanceTo(snake[i].position) < cubeSize / 2) {
alert("Game Over! Your score: " + (snake.length - 5));
resetGame();
return;
}
}
// Simple boundary conditions (example limit: 20 units)
var boundary = 20 * cubeSize;
if (Math.abs(head.position.x) > boundary || Math.abs(head.position.y) > boundary || Math.abs(head.position.z) > boundary) {
alert("Game Over! You hit the boundary. Your score: " + (snake.length - 5));
resetGame();
}
}
function growSnake() {
var snakeMaterial = new THREE.MeshLambertMaterial({ color: 0x00ff00 });
var geometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
var cube = new THREE.Mesh(geometry, snakeMaterial);
cube.position.copy(snake[snake.length - 1].position);
scene.add(cube);
snake.push(cube);
}
function resetGame() {
// Remove all snake cubes from the scene
for (var i = 0; i < snake.length; i++) {
scene.remove(snake[i]);
}
snake = [];
direction.set(1, 0, 0);
snakeLength = 5;
createSnake();
}
// Handle window resize
window.addEventListener('resize', onWindowResize, false);
function onWindowResize(){
camera.aspect = window.innerWidth/window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Initialize the game
createSnake();
createFood();
animate();
// ================================
// End of 3D Snake Game Code
// ================================
</script>
</body>
</html>
Instructions:
-
Copy the entire code above into a new text file.
-
Replace the placeholder in the code where it says to include the minified Three.js code with the actual minified code.
- Download the minified Three.js library from here.
- Copy the contents of the
three.min.js file.
- Paste it into the script tag where indicated in the code.
-
Save the file with a .html extension (e.g., 3d_snake_game.html).
-
Open the file in your web browser (preferably Chrome or Firefox).
Controls:
- Arrow Keys: Move the snake along the X and Y axes.
- W/S Keys: Move the snake along the Z axis.
Note:
- Ensure that your text editor can handle large files, as including the minified Three.js code will increase the size of the HTML file.
- The game includes basic collision detection and boundary handling.
- You start with a snake of length 5, and it grows each time you eat the food.
- The score is calculated based on how many food items you've collected.
Enjoy your game!