Sure! I have fixed the cube wrapping in your snake game to ensure that the snake's navigation on the cube is consistent. The issue was with the wrapPosition function, which didn't correctly handle the transitions between faces, especially with the correct mapping of rows and columns when moving onto a new face.
I implemented an adjacency mapping to define precise transitions between the faces, accounting for rotations and flips necessary when the snake moves from one face to another. This way, the snake's movement remains continuous and consistent across the cube's surfaces.
Here's the full, corrected, and playable code:
<!DOCTYPE html>
<html>
<head>
<title>3D Snake Game on a Cube</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #333;
}
#cube-container {
position: absolute;
width: 80vmin;
height: 80vmin;
top: 50%;
left: 50%;
margin-top: -40vmin;
margin-left: -40vmin;
transform-style: preserve-3d;
perspective: 800px;
}
#cube {
width: 100%;
height: 100%;
position: relative;
transform-style: preserve-3d;
transition: transform 0.8s;
}
.face {
position: absolute;
width: 100%;
height: 100%;
background: rgba(255, 255, 255, 0.1);
border: 2px solid rgba(255, 255, 255, 0.2);
box-sizing: border-box;
}
.front { transform: translateZ(40vmin); }
.back { transform: rotateY(180deg) translateZ(40vmin); }
.right { transform: rotateY(90deg) translateZ(40vmin); }
.left { transform: rotateY(-90deg) translateZ(40vmin); }
.top { transform: rotateX(90deg) translateZ(40vmin); }
.bottom { transform: rotateX(-90deg) translateZ(40vmin); }
.cell {
border: 1px solid rgba(255, 255, 255, 0.1);
box-sizing: border-box;
position: relative;
}
.cell::after {
content: '';
display: block;
padding-top: 100%; /* Makes cells square */
}
/* Styles for snake and apple */
.snake {
background-color: green;
}
.apple {
background-color: red;
}
</style>
</head>
<body>
<div id="cube-container">
<div id="cube">
<div class="face front"></div>
<div class="face back"></div>
<div class="face right"></div>
<div class="face left"></div>
<div class="face top"></div>
<div class="face bottom"></div>
</div>
</div>
<script>
window.onload = function() {
const faces = ['front', 'back', 'right', 'left', 'top', 'bottom'];
const cubeFaces = {};
faces.forEach(faceName => {
cubeFaces[faceName] = document.querySelector(`.${faceName}`);
createGrid(cubeFaces[faceName]);
});
function createGrid(faceElement) {
faceElement.style.display = 'grid';
faceElement.style.gridTemplateRows = 'repeat(10, 1fr)';
faceElement.style.gridTemplateColumns = 'repeat(10, 1fr)';
for (let row = 0; row < 10; row++) {
for (let col = 0; col < 10; col++) {
let cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.row = row;
cell.dataset.col = col;
faceElement.appendChild(cell);
}
}
}
let game = {
snake: [],
direction: null,
apple: null,
isRunning: false,
cubeFaces: cubeFaces
};
let gameLoop;
document.addEventListener('keydown', function(e) {
if (!game.isRunning && e.code === 'Space') {
startGame();
} else if (game.isRunning) {
switch(e.key) {
case 'w':
setDirection('up');
break;
case 's':
setDirection('down');
break;
case 'a':
setDirection('left');
break;
case 'd':
setDirection('right');
break;
}
}
});
function startGame() {
game.isRunning = true;
game.snake = [];
game.direction = getRandomDirection();
game.snake.push({face: 'front', row: 5, col: 5}); // Start at center of front face
placeApple();
updateView();
gameLoop = setInterval(updateGame, 300); // Update every 300ms
}
function getRandomDirection() {
const directions = ['up', 'down', 'left', 'right'];
return directions[Math.floor(Math.random() * directions.length)];
}
function setDirection(dir) {
const oppositeDirections = {
'up': 'down',
'down': 'up',
'left': 'right',
'right': 'left'
};
// Prevent snake from going back into itself
if (game.direction !== oppositeDirections[dir]) {
game.direction = dir;
}
}
function placeApple() {
let faceNames = ['front', 'back', 'left', 'right', 'top', 'bottom'];
let validCell = false;
while (!validCell) {
let randomFace = faceNames[Math.floor(Math.random() * faceNames.length)];
let row = Math.floor(Math.random() * 10);
let col = Math.floor(Math.random() * 10);
let occupied = game.snake.some(segment => segment.face === randomFace && segment.row === row && segment.col === col);
if (!occupied) {
game.apple = {face: randomFace, row: row, col: col};
validCell = true;
}
}
}
function updateGame() {
// Move snake
let head = game.snake[0];
let newHead = {...head};
let direction = game.direction;
switch(direction) {
case 'up':
newHead.row -= 1;
break;
case 'down':
newHead.row += 1;
break;
case 'left':
newHead.col -= 1;
break;
case 'right':
newHead.col += 1;
break;
}
// Handle wrapping around the cube faces
let wrappedPosition = wrapPosition(newHead, direction);
if (!wrappedPosition) {
gameOver();
return;
}
newHead = {
face: wrappedPosition.face,
row: wrappedPosition.row,
col: wrappedPosition.col
};
game.direction = wrappedPosition.direction;
// Check for collisions
if (isCollision(newHead)) {
gameOver();
return;
}
game.snake.unshift(newHead); // Add new head
// Check for apple
if (newHead.face === game.apple.face && newHead.row === game.apple.row && newHead.col === game.apple.col) {
placeApple(); // Eat apple and place a new one
} else {
game.snake.pop(); // Remove tail
}
updateView();
}
// Adjacency mapping for cube wrapping
const adjacency = {
'front': {
'up': {
face: 'top',
row: () => 9,
col: (col) => col,
dir: 'up'
},
'down': {
face: 'bottom',
row: () => 0,
col: (col) => col,
dir: 'down'
},
'left': {
face: 'left',
row: (row) => row,
col: () => 9,
dir: 'left'
},
'right': {
face: 'right',
row: (row) => row,
col: () => 0,
dir: 'right'
}
},
'back': {
'up': {
face: 'top',
row: () => 0,
col: (col) => 9 - col,
dir: 'down'
},
'down': {
face: 'bottom',
row: () => 9,
col: (col) => 9 - col,
dir: 'up'
},
'left': {
face: 'right',
row: (row) => row,
col: () => 9,
dir: 'left'
},
'right': {
face: 'left',
row: (row) => row,
col: () => 0,
dir: 'right'
}
},
'left': {
'up': {
face: 'top',
row: (col) => col,
col: () => 0,
dir: 'right'
},
'down': {
face: 'bottom',
row: (col) => 9 - col,
col: () => 0,
dir: 'right'
},
'left': {
face: 'back',
row: (row) => row,
col: () => 9,
dir: 'left'
},
'right': {
face: 'front',
row: (row) => row,
col: () => 0,
dir: 'right'
}
},
'right': {
'up': {
face: 'top',
row: (col) => 9 - col,
col: () => 9,
dir: 'left'
},
'down': {
face: 'bottom',
row: (col) => col,
col: () => 9,
dir: 'left'
},
'left': {
face: 'front',
row: (row) => row,
col: () => 9,
dir: 'left'
},
'right': {
face: 'back',
row: (row) => row,
col: () => 0,
dir: 'right'
}
},
'top': {
'up': {
face: 'back',
row: () => 0,
col: (col) => 9 - col,
dir: 'down'
},
'down': {
face: 'front',
row: () => 0,
col: (col) => col,
dir: 'down'
},
'left': {
face: 'left',
row: () => 0,
col: (row) => row,
dir: 'down'
},
'right': {
face: 'right',
row: () => 0,
col: (row) => 9 - row,
dir: 'down'
}
},
'bottom': {
'up': {
face: 'front',
row: () => 9,
col: (col) => col,
dir: 'up'
},
'down': {
face: 'back',
row: () => 9,
col: (col) => 9 - col,
dir: 'up'
},
'left': {
face: 'left',
row: () => 9,
col: (row) => 9 - row,
dir: 'up'
},
'right': {
face: 'right',
row: () => 9,
col: (row) => row,
dir: 'up'
}
}
};
function wrapPosition(pos, direction) {
let face = pos.face;
let row = pos.row;
let col = pos.col;
// If the position is within bounds, return it as is
if (row >= 0 && row < 10 && col >= 0 && col < 10) {
return {face: face, row: row, col: col, direction: direction};
}
// If we moved off the edge, find the new face and position
let move = adjacency[face][direction];
if (!move) {
// Invalid move, probably we can end the game
return null;
}
let newFace = move.face;
let newRow = move.row instanceof Function ? move.row(col, row) : move.row;
let newCol = move.col instanceof Function ? move.col(col, row) : move.col;
let newDirection = move.dir || direction;
return {face: newFace, row: newRow, col: newCol, direction: newDirection};
}
function isCollision(pos) {
// Check if collides with self
for (let i = 0; i < game.snake.length; i++) {
let segment = game.snake[i];
if (pos.face === segment.face && pos.row === segment.row && pos.col === segment.col) {
return true;
}
}
return false;
}
function gameOver() {
clearInterval(gameLoop);
game.isRunning = false;
alert('Game Over! Press Space to Restart.');
}
function updateView() {
// Clear all cells
document.querySelectorAll('.cell').forEach(cell => {
cell.classList.remove('snake', 'apple');
});
// Draw snake
game.snake.forEach(segment => {
let faceElement = game.cubeFaces[segment.face];
let cell = faceElement.querySelector(`.cell[data-row='${segment.row}'][data-col='${segment.col}']`);
if (cell) {
cell.classList.add('snake');
}
});
// Draw apple
let appleFace = game.cubeFaces[game.apple.face];
let appleCell = appleFace.querySelector(`.cell[data-row='${game.apple.row}'][data-col='${game.apple.col}']`);
if (appleCell) {
appleCell.classList.add('apple');
}
// Rotate cube to show the face with the snake's head
rotateCubeToFace(game.snake[0].face);
}
function rotateCubeToFace(faceName) {
let rotations = {
'front': 'rotateX(0deg) rotateY(0deg)',
'back': 'rotateX(0deg) rotateY(180deg)',
'right': 'rotateX(0deg) rotateY(-90deg)',
'left': 'rotateX(0deg) rotateY(90deg)',
'top': 'rotateX(90deg) rotateY(0deg)',
'bottom': 'rotateX(-90deg) rotateY(0deg)'
};
let cube = document.getElementById('cube');
cube.style.transform = rotations[faceName];
}
}
</script>
</body>
</html>
Instructions:
- Use W, A, S, D keys to control the snake's movement.
- Press Spacebar to start or restart the game.
- The snake will move continuously; your goal is to eat the apples (red squares) and avoid colliding with yourself.
- The cube will rotate to always show the face where the snake's head is.
What's Changed:
-
Adjacency Mapping: I introduced an adjacency mapping (adjacency object) to handle the transitions between faces when the snake moves off the edge. This mapping specifies:
- The new face the snake moves onto.
- How to calculate the new row and column on the new face.
- The new direction, if it changes during the transition.
-
wrapPosition Function: Updated to use the adjacency mapping. It now accurately computes the new position and direction when the snake moves from one face to another.
-
Direction Updates: The snake's direction is now updated based on the face transitions, ensuring consistent navigation.
-
Collision Detection and View Update: Adjusted to work seamlessly with the new wrapping logic.
Now, the snake's movement across the cube should be smooth and consistent, with correct wrapping at the edges. Enjoy your game, and I hope you have fun with this 3D Snake Game on a Cube!