Implement 3D Snake with HTML + JS + CSS. The entire code should be written in a single…
- User
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.
- Assistant
Creating a 3D Snake game on the surface of a cube involves handling movement across different faces, managing the snake's direction, and rendering the cube and snake with transparency and interactivity. Below is a complete HTML file with embedded CSS and JavaScript that implements the described game. The game initializes when the user presses the spacebar and allows control using the "W", "A", "S", and "D" keys.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>3D Snake on a Cube</title> <style> body, html { margin: 0; padding: 0; height: 100%; background: linear-gradient(135deg, #1e3c72, #2a5298); display: flex; justify-content: center; align-items: center; overflow: hidden; font-family: Arial, sans-serif; user-select: none; } #game-container { position: relative; width: 600px; height: 600px; perspective: 1000px; } .cube { width: 300px; height: 300px; position: absolute; transform-style: preserve-3d; transform: rotateX(-30deg) rotateY(-30deg); animation: rotate 20s linear infinite; opacity: 0.7; } .cube-face { position: absolute; width: 300px; height: 300px; border: 2px solid #fff; background: rgba(255, 255, 255, 0.1); } .front { transform: rotateY( 0deg) translateZ(150px); } .back { transform: rotateY(180deg) translateZ(150px); } .right { transform: rotateY( 90deg) translateZ(150px); } .left { transform: rotateY(-90deg) translateZ(150px); } .top { transform: rotateX( 90deg) translateZ(150px); } .bottom { transform: rotateX(-90deg) translateZ(150px); } @keyframes rotate { from { transform: rotateX(-30deg) rotateY(-30deg); } to { transform: rotateX(-30deg) rotateY(330deg); } } #info { position: absolute; top: 20px; left: 20px; color: #fff; font-size: 18px; background: rgba(0,0,0,0.5); padding: 10px 20px; border-radius: 10px; } canvas { position: absolute; top: 0; left: 0; } </style> </head> <body> <div id="game-container"> <div class="cube"> <div class="cube-face front"></div> <div class="cube-face back"></div> <div class="cube-face right"></div> <div class="cube-face left"></div> <div class="cube-face top"></div> <div class="cube-face bottom"></div> </div> <canvas id="gameCanvas" width="600" height="600"></canvas> <div id="info">Press SPACE to Start/Restart</div> </div> <script> const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const info = document.getElementById('info'); const cubeSize = 6; // Number of cells per face per row const cellSize = 50; // Pixel size of each cell const delay = 200; // Game speed in ms const faces = ['front', 'right', 'back', 'left', 'top', 'bottom']; let gameInterval; let direction = {x: 1, y: 0, face: 'front'}; // Initial direction let snake = []; let apple = {face: '', x: 0, y: 0}; let score = 0; let gameRunning = false; // Initialize game function init() { snake = [{face: 'front', x: Math.floor(cubeSize / 2), y: Math.floor(cubeSize /2)}]; placeApple(); score = 0; direction = getRandomDirection(); info.innerText = 'Press SPACE to Start/Restart'; draw(); } function getRandomDirection() { const dirs = [ {x: 1, y: 0, face: 'front'}, {x: -1, y: 0, face: 'front'}, {x: 0, y: 1, face: 'front'}, {x: 0, y: -1, face: 'front'}, // Add directions for other faces if needed ]; return dirs[Math.floor(Math.random() * dirs.length)]; } // Place apple at random position not occupied by snake function placeApple() { let valid = false; while (!valid) { const face = faces[Math.floor(Math.random() * faces.length)]; const x = Math.floor(Math.random() * cubeSize); const y = Math.floor(Math.random() * cubeSize); if (!snake.some(seg => seg.face === face && seg.x === x && seg.y === y)) { apple = {face, x, y}; valid = true; } } } // Handle key presses document.addEventListener('keydown', (e) => { if (e.code === 'Space') { if (gameRunning) { restartGame(); } else { startGame(); } } if (!gameRunning) return; switch (e.key.toLowerCase()) { case 'w': if (direction.y !== 1) direction = {x: 0, y: -1, face: direction.face}; break; case 's': if (direction.y !== -1) direction = {x: 0, y: 1, face: direction.face}; break; case 'a': if (direction.x !==1 ) direction = {x: -1, y: 0, face: direction.face}; break; case 'd': if (direction.x !== -1) direction = {x: 1, y: 0, face: direction.face}; break; } }); function startGame() { gameRunning = true; info.innerText = ''; gameInterval = setInterval(gameLoop, delay); } function restartGame() { clearInterval(gameInterval); init(); gameRunning = false; } function gameLoop() { const head = snake[0]; let newFace = head.face; let newX = head.x + direction.x; let newY = head.y + direction.y; // Handle wrapping to other faces if (newX < 0) { // Move to left face newFace = getAdjacentFace(head.face, 'left'); newX = cubeSize -1; } else if (newX >= cubeSize) { // Move to right face newFace = getAdjacentFace(head.face, 'right'); newX = 0; } if (newY < 0) { // Move to top face newFace = getAdjacentFace(head.face, 'top'); newY = cubeSize -1; } else if (newY >= cubeSize) { // Move to bottom face newFace = getAdjacentFace(head.face, 'bottom'); newY = 0; } const newHead = {face: newFace, x: newX, y: newY}; // Check collision with self if (snake.some(seg => seg.face === newHead.face && seg.x === newHead.x && seg.y === newHead.y)) { clearInterval(gameInterval); info.innerText = 'Game Over! Press SPACE to Restart'; gameRunning = false; return; } snake.unshift(newHead); // Check if apple is eaten if (newHead.face === apple.face && newHead.x === apple.x && newHead.y === apple.y) { score += 1; placeApple(); } else { snake.pop(); } // Update cube rotation to keep head face front updateCubeRotation(newHead.face); draw(); } function getAdjacentFace(currentFace, direction) { const adjacency = { front: {left: 'left', right: 'right', top: 'top', bottom: 'bottom'}, back: {left: 'right', right: 'left', top: 'top', bottom: 'bottom'}, left: {left: 'back', right: 'front', top: 'top', bottom: 'bottom'}, right: {left: 'front', right: 'back', top: 'top', bottom: 'bottom'}, top: {left: 'left', right: 'right', top: 'back', bottom: 'front'}, bottom: {left: 'left', right: 'right', top: 'front', bottom: 'back'}, }; return adjacency[currentFace][direction] || currentFace; } function updateCubeRotation(face) { const rotations = { front: 'rotateX(-30deg) rotateY(-30deg)', back: 'rotateX(-30deg) rotateY(150deg)', left: 'rotateX(-30deg) rotateY(-120deg)', right: 'rotateX(-30deg) rotateY(60deg)', top: 'rotateX(60deg) rotateY(-30deg)', bottom: 'rotateX(-120deg) rotateY(-30deg)', }; document.querySelector('.cube').style.transform = rotations[face]; } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw cube transparency (optional) // Draw snake snake.forEach((seg, index) => { drawCell(seg.face, seg.x, seg.y, index ===0 ? 'green' : 'darkgreen'); }); // Draw apple drawCell(apple.face, apple.x, apple.y, 'red'); // Draw score ctx.fillStyle = '#fff'; ctx.font = '20px Arial'; ctx.fillText(`Score: ${score}`, 10, canvas.height - 10); } function drawCell(face, x, y, color) { const faceCoords = getFaceCoordinates(face); const posX = faceCoords.x + x * cellSize; const posY = faceCoords.y + y * cellSize; ctx.fillStyle = color; ctx.fillRect(posX, posY, cellSize, cellSize); } function getFaceCoordinates(face) { const margin = 50; switch(face) { case 'front': return {x: margin, y: margin}; case 'back': return {x: margin *2 + cubeSize * cellSize, y: margin}; case 'left': return {x: 0, y: margin}; case 'right': return {x: margin *2 + cubeSize * cellSize, y: margin}; case 'top': return {x: margin, y: 0}; case 'bottom': return {x: margin, y: margin *2 + cubeSize * cellSize}; default: return {x: margin, y: margin}; } } // Start the game on page load init(); </script> </body> </html>Explanation of the Code
-
HTML Structure:
- The
#game-containerholds the 3D cube, the canvas for drawing the snake and apples, and an information div. - The cube is built using six divs with the class
cube-face, each representing a face of the cube (front,back,left,right,top,bottom). - A
canvaselement is used to render the snake, apples, and score.
- The
-
CSS Styling:
- The body has a gradient background and centers the game container.
- The
.cubeclass uses CSS 3D transforms to position the cube faces. It also includes a rotation animation to make the cube spin, enhancing the 3D effect. - The cube has reduced opacity to make it semi-transparent, allowing visibility of all faces and placed apples.
- The
#infodiv displays game instructions and game over messages.
-
JavaScript Functionality:
- Game Initialization: Sets up the snake in the center of the front face, places the first apple, and sets a random initial direction.
- Controls: Listens for keydown events to start/restart the game with the spacebar and controls the snake's direction with "W", "A", "S", "D".
- Game Loop: Moves the snake in the current direction, handles wrapping around the cube edges to adjacent faces, checks for collisions with itself, and places new apples when one is eaten.
- Rendering: Draws the snake, apples, and score on the canvas. The cube's rotation is updated to always bring the snake's head face to the front for better visibility.
- Utility Functions: Includes functions to determine adjacent faces, update rotation based on the snake's head position, and calculate face coordinates for rendering.
-
Gameplay:
- Press Spacebar to start or restart the game.
- Use W, A, S, D keys to control the snake's direction.
- The snake moves across the cube's surface, automatically wrapping to adjacent faces.
- The objective is to eat apples (red squares) to grow the snake without colliding with itself.
Notes
- This implementation uses a simple representation for the cube and maps the snake's movement across different faces. For a more sophisticated 3D rendering, WebGL or a 3D library like Three.js would be recommended, but that would require more complex code and potentially external assets.
- The cube rotation is manually controlled to face the snake's head towards the front, ensuring the player always has a clear view of the immediate playing area.
- The canvas draws the game elements in a 2D projection, simplifying the rendering process while maintaining the illusion of a 3D cube.
Feel free to customize the cube size, snake speed, colors, and other styles to enhance the game's appearance and difficulty.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.