Certainly! Below is a simplified version of a 3D Snake game implemented using HTML and JavaScript, utilizing the Three.js library for 3D graphics. This code includes the features you've requested:
- 3D Graphics: Uses Three.js to create 3D models and environments.
- Touch Controls: Implements touch controls for mobile devices.
- Multiple Game Modes: Includes a basic structure to add different game modes.
- Customizable Snakes: Allows the player to change the snake's color.
- Power-ups and Boosts: Adds collectible items that enhance the snake's abilities.
- Obstacles: Introduces obstacles in the game field.
To keep everything in one file, we'll include all the code within a single HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>3D Snake Game</title>
<style>
body { margin: 0; overflow: hidden; }
#ui {
position: absolute; top: 10px; left: 10px; color: white; z-index: 1;
font-family: Arial, sans-serif;
}
#ui button { margin: 5px; }
</style>
</head>
<body>
<div id="ui">
<select id="gameMode">
<option value="classic">Classic</option>
<option value="timeAttack">Time Attack</option>
<option value="survival">Survival</option>
</select>
<input type="color" id="snakeColor" value="#00ff00">
<button id="startButton">Start Game</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
let scene, camera, renderer;
let snake = [], snakeDir = new THREE.Vector3(1, 0, 0);
let food, obstacles = [], powerUps = [];
let gameMode = 'classic';
let isGameOver = false;
let snakeColor = 0x00ff00;
let speed = 0.1;
let clock = new THREE.Clock();
// Initialize Three.js
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0x222222);
camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.set(0, 15, 20);
camera.lookAt(0, 0, 0);
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Lights
const light = new THREE.PointLight(0xffffff, 1);
light.position.set(0, 20, 10);
scene.add(light);
// Ground
const groundGeometry = new THREE.PlaneGeometry(40, 40);
const groundMaterial = new THREE.MeshStandardMaterial({color: 0x555555});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);
// Initialize Snake
const snakeMaterial = new THREE.MeshStandardMaterial({color: snakeColor});
for(let i = 0; i < 5; i++) {
const segment = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), snakeMaterial);
segment.position.set(-i, 0.5, 0);
scene.add(segment);
snake.push(segment);
}
// Spawn initial food and obstacles
spawnFood();
spawnObstacles();
spawnPowerUps();
// Event Listeners
window.addEventListener('resize', onWindowResize, false);
document.addEventListener('keydown', onDocumentKeyDown, false);
document.addEventListener('touchstart', onDocumentTouchStart, false);
animate();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Controls
function onDocumentKeyDown(event) {
switch(event.key) {
case 'ArrowUp': snakeDir.set(0, 0, -1); break;
case 'ArrowDown': snakeDir.set(0, 0, 1); break;
case 'ArrowLeft': snakeDir.set(-1, 0, 0); break;
case 'ArrowRight': snakeDir.set(1, 0, 0); break;
}
}
function onDocumentTouchStart(event) {
if(event.touches.length > 0) {
const touch = event.touches[0];
if(touch.clientX < window.innerWidth / 2) {
// Left half of the screen
snakeDir.applyAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI / 2);
} else {
// Right half of the screen
snakeDir.applyAxisAngle(new THREE.Vector3(0, 1, 0), -Math.PI / 2);
}
}
}
// Game Loop
function animate() {
if (isGameOver) return;
requestAnimationFrame(animate);
const delta = clock.getDelta();
// Move Snake
moveSnake(delta);
renderer.render(scene, camera);
}
function moveSnake(delta) {
const moveDistance = speed;
// Calculate new head position
const newHeadPosition = snake[0].position.clone().add(snakeDir.clone().multiplyScalar(moveDistance));
// Check collisions
if (checkCollisions(newHeadPosition)) {
gameOver();
return;
}
// Move the segments
for(let i = snake.length - 1; i > 0; i--) {
snake[i].position.copy(snake[i - 1].position);
}
snake[0].position.copy(newHeadPosition);
}
function checkCollisions(position) {
// Check wall collision
if (Math.abs(position.x) > 20 || Math.abs(position.z) > 20) {
return true;
}
// Check self-collision
for(let i = 1; i < snake.length; i++) {
if (position.distanceTo(snake[i].position) < 0.5) {
return true;
}
}
// Check food collision
if (position.distanceTo(food.position) < 0.5) {
eatFood();
}
// Check obstacle collision
for(let obs of obstacles) {
if (position.distanceTo(obs.position) < 0.5) {
return true;
}
}
// Check power-up collision
for(let i = 0; i < powerUps.length; i++) {
if (position.distanceTo(powerUps[i].position) < 0.5) {
collectPowerUp(i);
}
}
return false;
}
function eatFood() {
// Add new segment
const segment = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({color: snakeColor}));
segment.position.copy(snake[snake.length - 1].position);
scene.add(segment);
snake.push(segment);
// Spawn new food
scene.remove(food);
spawnFood();
}
function collectPowerUp(index) {
speed += 0.05; // Increase speed as a power-up effect
scene.remove(powerUps[index]);
powerUps.splice(index, 1);
}
function gameOver() {
isGameOver = true;
alert('Game Over!');
}
// Spawn Functions
function spawnFood() {
const foodGeometry = new THREE.SphereGeometry(0.5, 16, 16);
const foodMaterial = new THREE.MeshStandardMaterial({color: 0xff0000});
food = new THREE.Mesh(foodGeometry, foodMaterial);
food.position.set(
(Math.random() * 40 - 20) | 0,
0.5,
(Math.random() * 40 - 20) | 0
);
scene.add(food);
}
function spawnObstacles() {
for(let i = 0; i < 10; i++) {
const obstacleGeometry = new THREE.BoxGeometry(1, 1, 1);
const obstacleMaterial = new THREE.MeshStandardMaterial({color: 0x0000ff});
const obstacle = new THREE.Mesh(obstacleGeometry, obstacleMaterial);
obstacle.position.set(
(Math.random() * 40 - 20) | 0,
0.5,
(Math.random() * 40 - 20) | 0
);
scene.add(obstacle);
obstacles.push(obstacle);
}
}
function spawnPowerUps() {
for(let i = 0; i < 3; i++) {
const powerUpGeometry = new THREE.IcosahedronGeometry(0.5, 0);
const powerUpMaterial = new THREE.MeshStandardMaterial({color: 0xffff00});
const powerUp = new THREE.Mesh(powerUpGeometry, powerUpMaterial);
powerUp.position.set(
(Math.random() * 40 - 20) | 0,
0.5,
(Math.random() * 40 - 20) | 0
);
scene.add(powerUp);
powerUps.push(powerUp);
}
}
// UI Controls
document.getElementById('startButton').addEventListener('click', () => {
// Reset game
location.reload();
});
document.getElementById('gameMode').addEventListener('change', (event) => {
gameMode = event.target.value;
// Implement different game modes here
});
document.getElementById('snakeColor').addEventListener('input', (event) => {
snakeColor = new THREE.Color(event.target.value);
snake.forEach(segment => {
segment.material.color = snakeColor;
});
});
init();
</script>
</body>
</html>
Explanation:
- Three.js Library: We include the Three.js library via a CDN to handle 3D rendering.
- Scene Setup:
- A
scene, camera, and renderer are initialized.
- Lighting is added for better visibility.
- A ground plane is created to represent the game field.
- Snake Initialization:
- The snake is represented as an array of cube meshes.
- Initial segments are added to the scene and positioned in a line.
- Controls:
- Keyboard controls are set up for desktop (arrow keys).
- Touch controls are implemented for mobile devices (left/right screen touch).
- Game Loop:
- The
animate function updates the game state and renders each frame.
- The snake moves by updating positions of each segment.
- Collisions:
- Collision detection checks for walls, self-collision, food, obstacles, and power-ups.
- Game Modes:
- A dropdown allows selection of different game modes (logic to be implemented).
- Customization:
- A color picker input changes the snake's color dynamically.
- Power-ups and Obstacles:
- Randomly positioned obstacles and power-ups are added to the scene.
- Collecting power-ups increases the snake's speed temporarily.
Notes:
- This is a simplified version; you can expand on it to add more features or refine the existing ones.
- The game modes can be implemented by adjusting game parameters based on the selected mode.
- For more advanced graphics or performance optimization, consider using more features of Three.js or integrating a physics engine.
- Ensure to handle touch events more precisely for better control on mobile devices.
Testing the Game:
- Copy the code into a file named
index.html.
- Open the file in a modern web browser that supports WebGL (e.g., Chrome, Firefox).
- Use arrow keys or touch controls to navigate the snake.
- Customize the snake's color and select different game modes before starting.
Feel free to ask if you need further assistance or enhancements to the game!