Implement 3D Snake with HTML + JS + CSS. The entire code should be written in a single HTML block with embedded JS and CSS. Don't use any remote assets. After opening the html, user will need to hit space to start / restart the game, the snake will randomly go in one direction at the start and use "wasd" to control the direction of the snake. The game will take place on the surface of a cube the snake will automatically curl around the sides of the cube when it reaches the edge and the cube will always be showing the face with the head of the snake on it. the cube will be see through / transparent so that we can always see what side the apples are on no matter where they spawn. Make it pretty and the background large.
current issues: snake is trapped on a single face it can move around freely on that face which is nice but when it gets to some of the edges it just stops as if running against a wall. sometimes it can travel to an upper face but once it gets there it just freezes in place being uncontrollable. everything else works great.
let snake = [];
let direction = null;
let apple = null;
let gameInterval = null;
let isGameOver = false;
let isGameStarted = false;
const messageElement = document.getElementById('message');
function spawnApple() {
let validCell = false;
while (!validCell) {
const face = Math.floor(Math.random() * 6);
const x = Math.floor(Math.random() * gridSize);
const y = Math.floor(Math.random() * gridSize);
// Check if apple is on snake
if (!snake.some(segment => segment.face === face && segment.x === x && segment.y === y)) {
apple = {face, x, y};
validCell = true;
}
}
drawCell(apple, 'apple');
}
function removeCell(cell) {
if (cell.element && cell.element.parentNode) {
cell.element.parentNode.removeChild(cell.element);
cell.element = null;
}
}
function gameLoop() {
if (isGameOver) return;
// Calculate new head position
const head = snake[0];
let newHead = {face: head.face, x: head.x, y: head.y};
switch (direction) {
case 'up':
newHead.y -=1;
break;
case 'down':
newHead.y +=1;
break;
case 'left':
newHead.x -=1;
break;
case 'right':
newHead.x +=1;
break;
default:
return; // No movement if direction is null
}
if (newHead.x < 0 || newHead.x >= gridSize || newHead.y < 0 || newHead.y >= gridSize) {
// Need to move to adjacent face
const adjacency = faceAdjacency[newHead.face][direction];
const adjFace = adjacency.face;
let adjX = adjacency.x;
let adjY = adjacency.y;
// Insert new head
snake.unshift(newHead);
drawCell(newHead, 'snake');
// Check if apple is eaten
if (apple.face === newHead.face && apple.x === newHead.x && apple.y === newHead.y) {
removeCell(apple);
spawnApple();
} else {
// Remove tail
const tail = snake.pop();
removeCell(tail);
}
// Rotate cube to show the face with snake's head
rotateCubeToFace(newHead.face);
}
function rotateCubeToFace(face){
// Reset transform
cube.style.transform = translate(-50%, -50%);
// Apply rotation
let rotationX = 0;
let rotationY = 0;
switch(face){
case 0: // Front
rotationY = 0;
break;
case 1: // Back
rotationY = 180;
break;
case 2: // Right
rotationY = -90;
break;
case 3: // Left
rotationY = 90;
break;
case 4: // Top
rotationX = -90;
break;
case 5: // Bottom
rotationX = 90;
break;
}
cube.style.transform += rotateX(rotationXdeg)rotateY({rotationY}deg);
}
function gameOver() {
isGameOver = true;
clearInterval(gameInterval);
messageElement.textContent = "Game Over! Press SPACE to restart";
}
if (e.key === 'w' || e.key === 'ArrowUp') {
if (direction !== 'down') direction = 'up';
} else if (e.key === 's' || e.key === 'ArrowDown') {
if (direction !== 'up') direction = 'down';
} else if (e.key === 'a' || e.key === 'ArrowLeft') {
if (direction !== 'right') direction = 'left';
} else if (e.key === 'd' || e.key === 'ArrowRight') {
if (direction !== 'left') direction = 'right';
}
});
// Start the game
initGame();
})();
It looks like you're encountering issues with the snake's movement across different faces of the cube, primarily due to how the face adjacency and coordinate transformations are handled. To resolve these issues, we'll need to:
Refine the Face Adjacency Logic: Ensure that when the snake moves off one face, it correctly transitions to the adjacent face with appropriate coordinate mapping.
Avoid Using eval: Using eval for coordinate calculations can lead to errors and is generally discouraged. We'll implement a safer and more reliable method.
Correct Cube Rotation Logic: Ensure that the cube rotates accurately to display the face where the snake's head currently resides.
Below is the revised and corrected version of your 3D Snake game. I've made the necessary adjustments to the JavaScript logic, improved the CSS for better visuals, and ensured that the movement across cube faces operates smoothly.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>3D Snake Game on Cube Surface</title>
<style>
body {
margin: 0;
overflow: hidden;
background: radial-gradient(circle at center, #000428, #004e92);
font-family: Arial, sans-serif;
color: white;
}
#game-container {
perspective: 1000px;
width: 100vw;
height: 100vh;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
#cube {
width: 300px;
height: 300px;
position: relative;
transform-style: preserve-3d;
transform: rotateX(-20deg) rotateY(45deg);
transition: transform 0.5s ease-out;
}
.face {
position: absolute;
width: 300px;
height: 300px;
background: rgba(255, 255, 255, 0.05);
border: 2px solid rgba(255, 255, 255, 0.2);
box-sizing: border-box;
}
/* Position each face */
#face-0 { /* Front */
transform: rotateY(0deg) translateZ(150px);
}
#face-1 { /* Back */
transform: rotateY(180deg) translateZ(150px);
}
#face-2 { /* Right */
transform: rotateY(90deg) translateZ(150px);
}
#face-3 { /* Left */
transform: rotateY(-90deg) translateZ(150px);
}
#face-4 { /* Top */
transform: rotateX(90deg) translateZ(150px);
}
#face-5 { /* Bottom */
transform: rotateX(-90deg) translateZ(150px);
}
/* Snake and apple cells */
.cell {
position: absolute;
width: 30px; /* Grid size 10x10 */
height: 30px;
box-sizing: border-box;
border-radius: 4px;
}
.snake {
background: #32CD32; /* LimeGreen */
}
.apple {
background: #FF4500; /* OrangeRed */
}
/* Message Styles */
#message {
position: absolute;
top: 20px;
width: 100%;
text-align: center;
color: white;
font-size: 24px;
z-index: 1000;
pointer-events: none;
}
</style>
</head>
<body>
<div id="game-container">
<div id="cube">
<div class="face" id="face-0"></div>
<div class="face" id="face-1"></div>
<div class="face" id="face-2"></div>
<div class="face" id="face-3"></div>
<div class="face" id="face-4"></div>
<div class="face" id="face-5"></div>
</div>
<div id="message">Press SPACE to start the game</div>
</div>
<script>
(function() {
const gridSize = 10; // 10x10 grid on each face
const cellSize = 30; // Must match CSS
const totalFaces = 6;
const cube = document.getElementById('cube');
const faceElements = Array.from({length: totalFaces}, (_, i) => document.getElementById(`face-${i}`));
let snake = [];
let direction = null;
let apple = null;
let gameInterval = null;
let isGameOver = false;
let isGameStarted = false;
const messageElement = document.getElementById('message');
// Define adjacency mapping for each face and direction
const faceAdjacency = {
0: { // Front
up: { face: 4, x: (x, y) => x, y: 0 }, // Top
down: { face: 5, x: x => x, y: gridSize - 1 }, // Bottom
left: { face: 3, x: gridSize -1, y: (x, y) => y }, // Left
right: { face: 2, x: 0, y: (x, y) => y } // Right
},
1: { // Back
up: { face: 4, x: (x, y) => gridSize - 1 - x, y: gridSize -1 }, // Top
down: { face: 5, x: (x, y) => gridSize - 1 -x, y:0 }, // Bottom
left: { face: 2, x: gridSize -1, y: (x, y) => y }, // Right
right: { face: 3, x: 0, y: (x, y) => y } // Left
},
2: { // Right
up: { face: 4, x: (x, y) => y, y: 0 }, // Top
down: { face: 5, x: (x, y) => gridSize -1 - y, y: gridSize -1 }, // Bottom
left: { face: 0, x: gridSize -1, y: (x, y) => y }, // Front
right: { face:1, x:0, y: (x, y) => y } // Back
},
3: { // Left
up: { face: 4, x: (x, y) => gridSize -1 - y, y:0 }, // Top
down: { face:5, x: (x, y) => y, y: gridSize -1 }, // Bottom
left: { face:1, x: gridSize -1, y: (x, y) => y }, // Back
right: { face:0, x:0, y: (x, y) => y } // Front
},
4: { // Top
up: { face:1, x: (x, y) => x, y:0 }, // Back
down: { face:0, x: (x, y) => x, y:0 }, // Front
left: { face:3, x: (x, y) => x, y:0 }, // Left
right: { face:2, x: (x, y) => x, y:0 } // Right
},
5: { // Bottom
up: { face:0, x: (x, y) => x, y: gridSize -1 }, // Front
down: { face:1, x: (x, y) => x, y: gridSize -1 }, // Back
left: { face:3, x: (x, y) => x, y: gridSize -1 }, // Left
right: { face:2, x: (x, y) => x, y: gridSize -1 } // Right
}
};
// Initialize the game
function initGame() {
// Clear previous game
snake.forEach(segment => {
removeCell(segment);
});
if (apple) removeCell(apple);
snake = [];
direction = null;
isGameOver = false;
isGameStarted = false;
messageElement.textContent = "Press SPACE to start the game";
// Initialize snake starting position
const startingFace = Math.floor(Math.random() * totalFaces);
const startingX = Math.floor(gridSize / 2);
const startingY = Math.floor(gridSize / 2);
direction = getRandomDirection();
const startingSegment = { face: startingFace, x: startingX, y: startingY };
snake.push(startingSegment);
drawCell(startingSegment, 'snake');
spawnApple();
rotateCubeToFace(startingFace);
}
// Get a random initial direction
function getRandomDirection() {
const dirs = ['up', 'down', 'left', 'right'];
return dirs[Math.floor(Math.random() * dirs.length)];
}
// Spawn an apple at a random position not occupied by the snake
function spawnApple() {
let valid = false;
while (!valid) {
const face = Math.floor(Math.random() * totalFaces);
const x = Math.floor(Math.random() * gridSize);
const y = Math.floor(Math.random() * gridSize);
// Check if the position is not occupied by the snake
if (!snake.some(segment => segment.face === face && segment.x === x && segment.y === y)) {
apple = { face, x, y };
drawCell(apple, 'apple');
valid = true;
}
}
}
// Draw a cell (snake segment or apple) on the specified face
function drawCell(cell, className) {
const cellDiv = document.createElement('div');
cellDiv.classList.add('cell', className);
cellDiv.style.left = `${cell.x * cellSize}px`;
cellDiv.style.top = `${cell.y * cellSize}px`;
faceElements[cell.face].appendChild(cellDiv);
cell.element = cellDiv;
}
// Remove a cell from the DOM
function removeCell(cell) {
if (cell.element && cell.element.parentNode) {
cell.element.parentNode.removeChild(cell.element);
}
}
// Main game loop
function gameLoop() {
if (isGameOver) return;
const head = snake[0];
let newHead = { face: head.face, x: head.x, y: head.y };
// Update position based on direction
switch (direction) {
case 'up':
newHead.y -= 1;
break;
case 'down':
newHead.y += 1;
break;
case 'left':
newHead.x -= 1;
break;
case 'right':
newHead.x += 1;
break;
}
// Check if new position is within the current face
if (newHead.x < 0 || newHead.x >= gridSize || newHead.y < 0 || newHead.y >= gridSize) {
// Transition to adjacent face
const dir = direction;
const adjacency = faceAdjacency[head.face][dir];
if (!adjacency) {
gameOver();
return;
}
// Calculate new coordinates based on adjacency mapping
newHead.face = adjacency.face;
// Determine new x and y using the provided functions or static values
if (typeof adjacency.x === 'function') {
newHead.x = adjacency.x(head.x, head.y);
} else {
newHead.x = adjacency.x;
}
if (typeof adjacency.y === 'function') {
newHead.y = adjacency.y(head.x, head.y);
} else {
newHead.y = adjacency.y;
}
// Validate new coordinates
if (newHead.x < 0 || newHead.x >= gridSize || newHead.y < 0 || newHead.y >= gridSize) {
gameOver();
return;
}
}
// Check for self-collision
if (snake.some(segment => segment.face === newHead.face && segment.x === newHead.x && segment.y === newHead.y)) {
gameOver();
return;
}
// Add new head to the snake
snake.unshift(newHead);
drawCell(newHead, 'snake');
// Check if apple is eaten
if (apple.face === newHead.face && apple.x === newHead.x && apple.y === newHead.y) {
removeCell(apple);
spawnApple();
} else {
// Remove tail segment
const tail = snake.pop();
removeCell(tail);
}
// Rotate cube to show the current face
rotateCubeToFace(newHead.face);
}
// Rotate the cube to bring the specified face to the front
function rotateCubeToFace(face) {
let rotationX = -20;
let rotationY = 45;
switch(face) {
case 0: // Front
rotationX = -20;
rotationY = 45;
break;
case 1: // Back
rotationX = -20;
rotationY = 225;
break;
case 2: // Right
rotationX = -20;
rotationY = -45;
break;
case 3: // Left
rotationX = -20;
rotationY = 135;
break;
case 4: // Top
rotationX = 70;
rotationY = 45;
break;
case 5: // Bottom
rotationX = -110;
rotationY = 45;
break;
}
cube.style.transform = `rotateX(${rotationX}deg) rotateY(${rotationY}deg)`;
}
// Handle game over state
function gameOver() {
isGameOver = true;
clearInterval(gameInterval);
messageElement.textContent = "Game Over! Press SPACE to restart";
}
// Handle key inputs for direction and game control
document.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
if (isGameOver || !isGameStarted) {
initGame();
isGameStarted = true;
messageElement.textContent = "";
direction = direction || getRandomDirection();
gameInterval = setInterval(gameLoop, 300);
}
}
if (!isGameStarted) return; // Ignore direction keys if game hasn't started
switch(e.key.toLowerCase()) {
case 'w':
case 'arrowup':
if (direction !== 'down') direction = 'up';
break;
case 's':
case 'arrowdown':
if (direction !== 'up') direction = 'down';
break;
case 'a':
case 'arrowleft':
if (direction !== 'right') direction = 'left';
break;
case 'd':
case 'arrowright':
if (direction !== 'left') direction = 'right';
break;
}
});
// Start the game on page load
initGame();
})();
</script>
</body>
</html>
Explanation of the Changes:
Refined Face Adjacency Mapping:
Replaced the previous adjacency mapping that used string placeholders and eval. Instead, each direction (up, down, left, right) for a face now has a clear mapping to the adjacent face along with functions to calculate the new x and y coordinates based on the current position.
This approach ensures accurate and safe coordinate transformations when transitioning between faces.
Coordinate Transformation:
Instead of using eval to parse and calculate new coordinates, we use functions that take the current x and y and return the new coordinates. This method is more reliable and avoids the pitfalls of using eval.
Cube Rotation Logic:
Updated the rotateCubeToFace function to apply specific rotateX and rotateY values based on the target face. This ensures that when the cube rotates, the correct face is brought to the front.
Removed the incorrect translate(-50%, -50%) which was causing transformation issues.
Enhanced CSS for Better Visibility:
Increased the border thickness and adjusted the background transparency of the cube faces for better visual distinction.
Added border-radius to the snake and apple cells for a smoother appearance.
Improved Game Flow Control:
Ensured that the game only starts or restarts when the user presses the SPACE key.
Added safeguards to prevent changing direction when the game hasn't started, avoiding unintended behavior.
Sanity Checks:
Added checks to ensure that the new head position after a face transition is within valid bounds. If not, the game will end gracefully.
Optimized Event Handling:
Consolidated the key event handling to make it more readable and maintainable.
Additional Recommendations:
Responsive Design: Consider making the cube size responsive based on the viewport size to ensure consistent gameplay across different devices.
Difficulty Levels: Introduce varying speeds or obstacles to increase the game's difficulty as the snake grows longer.
Score Tracking: Implement a scoring system to keep track of the player's progress.
With these changes, the snake should now move seamlessly across all faces of the cube without getting stuck or freezing. The cube will rotate to always display the face where the snake's head is located, providing a clear and engaging visual experience.
Feel free to further customize the styles and game mechanics to enhance the gameplay experience!