Sure! Below is a simple 3D Snake game implemented using HTML, CSS, and JavaScript all in one file. This game uses the HTML Canvas element and vanilla JavaScript to create a basic 3D effect for the snake. The snake moves around a grid, and the goal is to collect as many apples as possible without running into walls or the snake's own body.
You can copy the entire code below and save it as an .html file, then open it in a web browser to play the game.
html
<!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;
}
#score {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
color: #0f0;
font-family: monospace;
font-size: 24px;
z-index: 1;
}
</style>
</head>
<body>
<div id="score">Score: 0</div>
<canvas id="gameCanvas"></canvas>
<script>
// Get the canvas and context
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Game variables
const gridSize = 20;
const tileSize = Math.floor(Math.min(canvas.width, canvas.height) / gridSize);
let snake = [{ x: 10, y: 10 }];
let direction = { x: 0, y: 0 };
let apple = { x: 5, y: 5 };
let score = 0;
// Handle keyboard input
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' && direction.y !== 1) {
direction = { x: 0, y: -1 };
} else if (e.key === 'ArrowDown' && direction.y !== -1) {
direction = { x: 0, y: 1 };
} else if (e.key === 'ArrowLeft' && direction.x !== 1) {
direction = { x: -1, y: 0 };
} else if (e.key === 'ArrowRight' && direction.x !== -1) {
direction = { x: 1, y: 0 };
}
});
// Game loop
function gameLoop() {
update();
draw();
setTimeout(gameLoop, 100);
}
// Update game state
function update() {
// Move snake
const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
// Wrap around the edges
if (head.x < 0) head.x = gridSize - 1;
if (head.x >= gridSize) head.x = 0;
if (head.y < 0) head.y = gridSize - 1;
if (head.y >= gridSize) head.y = 0;
// Check for collision with self
if (snake.some(segment => segment.x === head.x && segment.y === head.y)) {
// Game over
alert('Game Over! Your score: ' + score);
snake = [{ x: 10, y: 10 }];
direction = { x: 0, y: 0 };
score = 0;
document.getElementById('score').innerText = 'Score: ' + score;
return;
}
snake.unshift(head);
// Check for apple collision
if (head.x === apple.x && head.y === apple.y) {
score++;
document.getElementById('score').innerText = 'Score: ' + score;
placeApple();
} else {
snake.pop();
}
}
// Draw everything
function draw() {
// Clear canvas
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw snake with 3D effect
for (let i = 0; i < snake.length; i++) {
const segment = snake[i];
const size = tileSize * (1 + (i / snake.length) * 0.3);
const x = segment.x * tileSize + (tileSize - size) / 2;
const y = segment.y * tileSize + (tileSize - size) / 2;
const depthColor = Math.floor(255 - (i / snake.length) * 100);
ctx.fillStyle = `rgb(0, ${depthColor}, 0)`;
ctx.fillRect(x, y, size, size);
}
// Draw apple
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.arc(
apple.x * tileSize + tileSize / 2,
apple.y * tileSize + tileSize / 2,
tileSize / 2,
0,
Math.PI * 2
);
ctx.fill();
}
// Place apple at random position
function placeApple() {
apple.x = Math.floor(Math.random() * gridSize);
apple.y = Math.floor(Math.random() * gridSize);
// Ensure apple doesn't spawn on the snake
while (snake.some(segment => segment.x === apple.x && segment.y === apple.y)) {
apple.x = Math.floor(Math.random() * gridSize);
apple.y = Math.floor(Math.random() * gridSize);
}
}
// Start the game
gameLoop();
</script>
</body>
</html>
Instructions:
Copy the entire code above.
Paste it into a text editor and save the file with an .html extension (e.g., 3d_snake_game.html).
Open the saved file in a modern web browser (like Chrome, Firefox, or Edge).
Use the arrow keys to control the snake.
How the Game Works:
Canvas Setup:
The game uses an HTML <canvas> element that fills the entire browser window.
The canvas dimensions are set to match the window size, and the game grid is calculated based on the gridSize variable.
Snake Movement:
The snake is represented as an array of segment positions.
The direction object keeps track of the current movement direction.
On each update, a new head position is calculated and added to the front of the snake array.
If the snake doesn't eat an apple, the last segment is removed (snake.pop()), effectively moving the snake forward.
Collision Detection:
The game checks if the snake has collided with itself by checking if the new head position matches any existing segment.
If a collision is detected, the game is reset after showing an alert with the score.
Apple Placement and Collection:
An apple is placed at a random position on the grid.
If the snake's head reaches the apple, the score is incremented, and a new apple is placed.
The snake grows by not removing the last segment when an apple is eaten.
3D Effect:
The 3D effect is simulated by changing the size and color intensity of the snake segments.
Segments closer to the tail are drawn smaller and with a darker green color.
This creates a pseudo-3D appearance, giving depth to the snake.
Controls:
The arrow keys change the direction of the snake unless it would cause the snake to move back into itself (preventing a 180-degree turn).
Game Loop:
The gameLoop function updates the game state and renders the graphics.
It uses setTimeout to continuously run at a set interval (100 milliseconds).
Feel free to customize the game:
Speed: Adjust the setTimeout delay in the gameLoop function to change the game speed.
Grid Size: Change the gridSize variable for a larger or smaller playing field.
Appearance: Modify the colors and styles in the CSS and drawing functions to change the game's look.
Enjoy playing the game and experimenting with the code!