Certainly! Below is a complete HTML file that implements a 3D Snake game using HTML, CSS, and JavaScript. The game initializes with the snake moving in a random direction. You can control the snake using the W, A, S, and D keys, and press the Space bar to start or restart the game. The design includes a visually appealing 3D effect and a large, immersive background.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>3D Snake Game</title>
<style>
body, html {
margin: 0;
padding: 0;
overflow: hidden;
background: #1e1e1e;
height: 100%;
width: 100%;
font-family: Arial, sans-serif;
}
#game-container {
position: relative;
width: 100vw;
height: 100vh;
perspective: 800px;
background: linear-gradient(to top, #0f2027, #203a43, #2c5364);
display: flex;
justify-content: center;
align-items: center;
}
#game {
position: relative;
width: 600px;
height: 600px;
transform-style: preserve-3d;
transform: rotateX(45deg) rotateZ(45deg);
background: rgba(255, 255, 255, 0.05);
border: 2px solid #fff;
box-shadow: 0 0 20px rgba(255,255,255,0.1);
}
.cube {
position: absolute;
width: 20px;
height: 20px;
background: #4caf50;
transform-style: preserve-3d;
transition: transform 0.1s linear;
}
.food {
background: #f44336;
}
#message {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
font-size: 24px;
text-align: center;
z-index: 10;
display: none;
}
#instructions {
position: absolute;
bottom: 20px;
width: 100%;
text-align: center;
color: #fff;
font-size: 14px;
}
</style>
</head>
<body>
<div id="game-container">
<div id="game"></div>
<div id="message">
<div>Press Space to Start</div>
<div style="font-size: 16px; margin-top: 10px;">Use W/A/S/D to Control</div>
</div>
<div id="instructions">
<p>3D Snake Game - Use W (Up), S (Down), A (Left), D (Right). Press Space to Start/Restart.</p>
</div>
</div>
<script>
const gameElement = document.getElementById('game');
const messageElement = document.getElementById('message');
const gridSize = 30;
const cubeSize = 20;
let snake = [];
let direction = { x: 1, y: 0 };
let food = null;
let gameInterval = null;
let gameRunning = false;
function init() {
snake = [{ x: Math.floor(gridSize / 2), y: Math.floor(gridSize / 2) }];
direction = getRandomDirection();
placeFood();
render();
}
function getRandomDirection() {
const dirs = [
{ x: 1, y: 0 },
{ x: -1, y: 0 },
{ x: 0, y: 1 },
{ x: 0, y: -1 }
];
return dirs[Math.floor(Math.random() * dirs.length)];
}
function placeFood() {
let newFood;
do {
newFood = {
x: Math.floor(Math.random() * gridSize),
y: Math.floor(Math.random() * gridSize)
};
} while (snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
food = newFood;
}
function render() {
gameElement.innerHTML = '';
// Render food
const foodCube = document.createElement('div');
foodCube.classList.add('cube', 'food');
setPosition(foodCube, food.x, food.y, 0);
gameElement.appendChild(foodCube);
// Render snake
snake.forEach((segment, index) => {
const cube = document.createElement('div');
cube.classList.add('cube');
setPosition(cube, segment.x, segment.y, index);
gameElement.appendChild(cube);
});
}
function setPosition(element, x, y, z) {
const spacing = 20;
element.style.transform = `translate3d(${(x - gridSize / 2) * spacing}px, ${(y - gridSize / 2) * spacing}px, ${z * spacing}px)`;
}
function update() {
const head = { ...snake[0] };
head.x += direction.x;
head.y += direction.y;
// Wrap around
head.x = (head.x + gridSize) % gridSize;
head.y = (head.y + gridSize) % gridSize;
// Check self-collision
if (snake.some(segment => segment.x === head.x && segment.y === head.y)) {
endGame();
return;
}
snake.unshift(head);
// Check food collision
if (head.x === food.x && head.y === food.y) {
placeFood();
} else {
snake.pop();
}
render();
}
function startGame() {
if (gameRunning) return;
gameRunning = true;
messageElement.style.display = 'none';
init();
gameInterval = setInterval(update, 200);
}
function endGame() {
clearInterval(gameInterval);
gameRunning = false;
messageElement.innerHTML = '<div>Game Over</div><div>Press Space to Restart</div>';
messageElement.style.display = 'block';
}
document.addEventListener('keydown', (e) => {
if (e.code === 'Space') {
if (!gameRunning) {
startGame();
}
}
if (!gameRunning) return;
switch (e.key.toLowerCase()) {
case 'w':
if (direction.y === 0) {
direction = { x: 0, y: -1 };
}
break;
case 's':
if (direction.y === 0) {
direction = { x: 0, y: 1 };
}
break;
case 'a':
if (direction.x === 0) {
direction = { x: -1, y: 0 };
}
break;
case 'd':
if (direction.x === 0) {
direction = { x: 1, y: 0 };
}
break;
}
});
// Prevent arrow keys from scrolling the page
window.addEventListener("keydown", function(e) {
if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"," "].indexOf(e.key) > -1) {
e.preventDefault();
}
}, false);
</script>
</body>
</html>
Features Implemented:
-
3D Effect: The snake and food are rendered using CSS 3D transforms to give a depth illusion. Each segment of the snake is layered in the z-axis to enhance the 3D appearance.
-
Controls:
- Start/Restart: Press
Space to start or restart the game.
- Navigation: Use
W (Up), A (Left), S (Down), and D (Right) keys to control the snake's direction.
-
Gameplay Mechanics:
- Random Initial Direction: The snake starts moving in a random direction each time the game starts.
- Food Placement: Food appears at random positions on the grid, and consuming it increases the snake's length.
- Collision Detection: The game ends if the snake collides with itself.
-
Visual Design:
- Background: A gradient background creates a visually appealing environment.
- Snake and Food: The snake is green, and the food is red to stand out against the background.
- Responsive Layout: The game container adjusts to the viewport size, ensuring it looks good on various screens.
-
User Instructions: Instructions are provided at the bottom of the screen to guide the player.
How to Use:
- Start the Game: Open the HTML file in your browser and press the
Space bar to start the game.
- Control the Snake: Use the
W, A, S, and D keys to navigate the snake around the grid.
- Restarting: If the game ends due to a collision, press the
Space bar to restart.
Enjoy playing the 3D Snake game!