Write code for a 3D version of Snake in NextJS, using TypeScript.
Assistant
Creating a 3D version of the classic Snake game using Next.js and TypeScript is an exciting project that combines web development with 3D graphics programming. We'll use Three.js, a popular 3D library for JavaScript, to handle the rendering of the 3D scene within our Next.js application.
Below is a step-by-step guide to building the game:
Set Up the Next.js App with TypeScript
Install Necessary Dependencies
Create the 3D Scene with Three.js
Implement the Snake Game Logic
Handle User Input
Animate and Render the Game Loop
Let's get started!
1. Set Up the Next.js App with TypeScript
First, create a new Next.js project with TypeScript support.
We'll need Three.js for 3D rendering and @types/three for TypeScript types.
bash
npm install three
npm install --save-dev @types/three
3. Create the 3D Scene with Three.js
We'll set up a basic Three.js scene within a Next.js page.
Create a Canvas Component
Create a new component at components/ThreeCanvas.tsx:
tsx
// components/ThreeCanvas.tsx
import { useRef, useEffect } from 'react';
import * as THREE from 'three';
const ThreeCanvas = () => {
const mountRef = useRef<HTMLDivElement>(null);
useEffect(() => {
// Set up the scene
const scene = new THREE.Scene();
// Set up the camera
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.z = 5;
// Set up the renderer
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// Append renderer to DOM
mountRef.current?.appendChild(renderer.domElement);
// Add a simple cube
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// Animation loop
const animate = () => {
requestAnimationFrame(animate);
// Rotate the cube for demonstration
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
// Clean up on unmount
return () => {
mountRef.current?.removeChild(renderer.domElement);
};
}, []);
return <div ref={mountRef} />;
};
export default ThreeCanvas;
Use the Component in a Page
Update pages/index.tsx to include the ThreeCanvas component.
We need to represent the snake, the food, and handle the game state.
Define the Snake and Food
We'll represent the snake as an array of 3D cubes.
tsx
// components/ThreeCanvas.tsx
// ... previous imports ...
type Vector3 = THREE.Vector3;
interface SnakeSegment {
mesh: THREE.Mesh;
position: Vector3;
}
const ThreeCanvas = () => {
// ... previous code ...
useEffect(() => {
// ... previous setup code ...
// Snake parameters
const snakeSegments: SnakeSegment[] = [];
const segmentSize = 1;
const initialLength = 5;
let direction = new Vector3(1, 0, 0); // Moving along X-axis initially
let canChangeDirection = true;
// Create initial snake
for (let i = 0; i < initialLength; i++) {
const segmentGeometry = new THREE.BoxGeometry(segmentSize, segmentSize, segmentSize);
const segmentMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const segmentMesh = new THREE.Mesh(segmentGeometry, segmentMaterial);
const position = new Vector3(-i * segmentSize, 0, 0);
segmentMesh.position.copy(position);
snakeSegments.push({ mesh: segmentMesh, position });
scene.add(segmentMesh);
}
// Food
const foodGeometry = new THREE.BoxGeometry(segmentSize, segmentSize, segmentSize);
const foodMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const foodMesh = new THREE.Mesh(foodGeometry, foodMaterial);
const foodPosition = new Vector3(
Math.floor(Math.random() * 10 - 5),
Math.floor(Math.random() * 10 - 5),
Math.floor(Math.random() * 10 - 5)
);
foodMesh.position.copy(foodPosition);
scene.add(foodMesh);
// ... rest of the code ...
5. Handle User Input
We'll capture keyboard events to change the snake's direction.
tsx
// ... inside useEffect ...
// Handle keyboard input
const onKeyDown = (event: KeyboardEvent) => {
if (!canChangeDirection) return;
const keyDirectionMap: { [key: string]: Vector3 } = {
ArrowUp: new Vector3(0, 1, 0),
ArrowDown: new Vector3(0, -1, 0),
ArrowLeft: new Vector3(-1, 0, 0),
ArrowRight: new Vector3(1, 0, 0),
KeyW: new Vector3(0, 0, -1),
KeyS: new Vector3(0, 0, 1),
};
const newDirection = keyDirectionMap[event.code];
if (newDirection && !newDirection.equals(direction.clone().negate())) {
direction = newDirection;
canChangeDirection = false; // Prevent immediate reversal
}
};
window.addEventListener('keydown', onKeyDown);
// Clean up event listener on unmount
return () => {
window.removeEventListener('keydown', onKeyDown);
mountRef.current?.removeChild(renderer.domElement);
};
6. Animate and Render the Game Loop
We'll update the snake's position in a game loop.
tsx
// ... inside useEffect ...
let lastUpdateTime = performance.now();
const moveInterval = 200; // Move every 200ms
const animate = () => {
requestAnimationFrame(animate);
const currentTime = performance.now();
if (currentTime - lastUpdateTime > moveInterval) {
lastUpdateTime = currentTime;
canChangeDirection = true;
// Move the snake
const newHeadPosition = snakeSegments[0].position.clone().add(direction.multiplyScalar(segmentSize));
// Check for collisions with walls (you can define boundaries as needed)
// Here we wrap around for simplicity
newHeadPosition.x = ((newHeadPosition.x + 10) % 20) - 10;
newHeadPosition.y = ((newHeadPosition.y + 10) % 20) - 10;
newHeadPosition.z = ((newHeadPosition.z + 10) % 20) - 10;
// Check for collisions with self
for (let i = 0; i < snakeSegments.length; i++) {
if (newHeadPosition.equals(snakeSegments[i].position)) {
alert('Game Over');
window.location.reload();
}
}
// Check for food collision
if (newHeadPosition.equals(foodPosition)) {
// Extend the snake
const segmentGeometry = new THREE.BoxGeometry(segmentSize, segmentSize, segmentSize);
const segmentMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const segmentMesh = new THREE.Mesh(segmentGeometry, segmentMaterial);
const position = newHeadPosition.clone();
segmentMesh.position.copy(position);
snakeSegments.unshift({ mesh: segmentMesh, position });
scene.add(segmentMesh);
// Reposition food
foodPosition.set(
Math.floor(Math.random() * 10 - 5),
Math.floor(Math.random() * 10 - 5),
Math.floor(Math.random() * 10 - 5)
);
foodMesh.position.copy(foodPosition);
} else {
// Move the snake
const tail = snakeSegments.pop();
if (tail) {
tail.position.copy(newHeadPosition);
tail.mesh.position.copy(newHeadPosition);
snakeSegments.unshift(tail);
}
}
}
renderer.render(scene, camera);
};
animate();
7. Full Code for ThreeCanvas.tsx
Putting it all together, here's the full code for the ThreeCanvas component.
tsx
// components/ThreeCanvas.tsx
import { useRef, useEffect } from 'react';
import * as THREE from 'three';
type Vector3 = THREE.Vector3;
interface SnakeSegment {
mesh: THREE.Mesh;
position: Vector3;
}
const ThreeCanvas = () => {
const mountRef = useRef<HTMLDivElement>(null);
useEffect(() => {
// Set up the scene
const scene = new THREE.Scene();
// Set up the camera
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.set(0, 10, 20);
camera.lookAt(0, 0, 0);
// Set up the renderer
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// Append renderer to DOM
mountRef.current?.appendChild(renderer.domElement);
// Add lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.6);
directionalLight.position.set(0, 10, 10);
scene.add(directionalLight);
// Ground plane
const planeGeometry = new THREE.PlaneGeometry(50, 50, 10, 10);
const planeMaterial = new THREE.MeshStandardMaterial({ color: 0x808080 });
const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial);
planeMesh.rotation.x = -Math.PI / 2;
scene.add(planeMesh);
// Snake parameters
const snakeSegments: SnakeSegment[] = [];
const segmentSize = 1;
const initialLength = 5;
let direction = new Vector3(1, 0, 0); // Moving along X-axis initially
let canChangeDirection = true;
// Create initial snake
for (let i = 0; i < initialLength; i++) {
const segmentGeometry = new THREE.BoxGeometry(segmentSize, segmentSize, segmentSize);
const segmentMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const segmentMesh = new THREE.Mesh(segmentGeometry, segmentMaterial);
const position = new Vector3(-i * segmentSize, 0.5, 0);
segmentMesh.position.copy(position);
snakeSegments.push({ mesh: segmentMesh, position });
scene.add(segmentMesh);
}
// Food
const foodGeometry = new THREE.BoxGeometry(segmentSize, segmentSize, segmentSize);
const foodMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 });
const foodMesh = new THREE.Mesh(foodGeometry, foodMaterial);
const foodPosition = new Vector3(
Math.floor(Math.random() * 20 - 10),
0.5,
Math.floor(Math.random() * 20 - 10)
);
foodMesh.position.copy(foodPosition);
scene.add(foodMesh);
// Handle keyboard input
const onKeyDown = (event: KeyboardEvent) => {
if (!canChangeDirection) return;
const keyDirectionMap: { [key: string]: Vector3 } = {
ArrowUp: new Vector3(0, 0, -1),
ArrowDown: new Vector3(0, 0, 1),
ArrowLeft: new Vector3(-1, 0, 0),
ArrowRight: new Vector3(1, 0, 0),
};
const newDirection = keyDirectionMap[event.code];
if (newDirection && !newDirection.equals(direction.clone().negate())) {
direction = newDirection;
canChangeDirection = false; // Prevent immediate reversal
}
};
window.addEventListener('keydown', onKeyDown);
let lastUpdateTime = performance.now();
const moveInterval = 200; // Move every 200ms
const animate = () => {
requestAnimationFrame(animate);
const currentTime = performance.now();
if (currentTime - lastUpdateTime > moveInterval) {
lastUpdateTime = currentTime;
canChangeDirection = true;
// Move the snake
const newHeadPosition = snakeSegments[0].position.clone().add(direction.multiplyScalar(segmentSize));
// Wrap around boundaries
newHeadPosition.x = ((newHeadPosition.x + 25) % 50) - 25;
newHeadPosition.z = ((newHeadPosition.z + 25) % 50) - 25;
// Check for collisions with self
for (let i = 0; i < snakeSegments.length; i++) {
if (newHeadPosition.equals(snakeSegments[i].position)) {
alert('Game Over');
window.location.reload();
}
}
// Check for food collision
if (newHeadPosition.equals(foodPosition)) {
// Extend the snake
const segmentGeometry = new THREE.BoxGeometry(segmentSize, segmentSize, segmentSize);
const segmentMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const segmentMesh = new THREE.Mesh(segmentGeometry, segmentMaterial);
const position = newHeadPosition.clone();
segmentMesh.position.copy(position);
snakeSegments.unshift({ mesh: segmentMesh, position });
scene.add(segmentMesh);
// Reposition food
foodPosition.set(
Math.floor(Math.random() * 20 - 10),
0.5,
Math.floor(Math.random() * 20 - 10)
);
foodMesh.position.copy(foodPosition);
} else {
// Move the snake
const tail = snakeSegments.pop();
if (tail) {
tail.position.copy(newHeadPosition);
tail.mesh.position.copy(newHeadPosition);
snakeSegments.unshift(tail);
}
}
}
renderer.render(scene, camera);
};
animate();
// Clean up on unmount
return () => {
window.removeEventListener('keydown', onKeyDown);
mountRef.current?.removeChild(renderer.domElement);
};
}, []);
return <div ref={mountRef} />;
};
export default ThreeCanvas;
8. Run the Application
Start the development server:
bash
npm run dev
Navigate to http://localhost:3000 in your browser. You should see a 3D snake moving on the screen. Use the arrow keys to control the snake. The game will restart when you collide with yourself.
Explanation
Three.js Setup: We initialize a basic Three.js scene within a Next.js component, setting up a camera, renderer, and adding it to the DOM.
Snake Representation: The snake is an array of segments, each segment being a THREE.Mesh with a position. We manipulate these positions to move the snake.
Movement Logic: At each interval, we calculate the new head position based on the current direction and move the segments accordingly.
User Input: Keyboard events are used to change the direction of the snake, ensuring that it cannot reverse on itself.
Collision Detection: We check for collisions with the snake's body and food, handling growth and game over conditions.
Game Loop: The animate function handles the game loop, updating the game state and rendering the scene.
Notes
Styling and Responsiveness: For simplicity, styles are minimal. You can enhance the UI and make the canvas responsive.
Improvements: This is a basic implementation. Additional features like score tracking, levels, and better graphics can be added.
Performance: For better performance, especially with a larger snake, consider optimizing the rendering and updating logic.
Dependencies
Ensure your package.json has the necessary dependencies:
By following the above steps, you should have a functioning 3D Snake game built with Next.js and TypeScript. This project demonstrates how to integrate Three.js into a Next.js application and handles basic game development concepts in a web environment.