I'll help you create a Snake game in React with TypeScript, containerize it with Docker, and expose it on port 8085. I'll break this down into multiple files:
- First, let's create the project structure:
snake-game/
│
├── Dockerfile
├── docker-compose.yml
├── package.json
├── tsconfig.json
├── next.config.js
│
└── src/
├── pages/
│ └── index.tsx
├── components/
│ └── SnakeGame.tsx
└── styles/
└── SnakeGame.module.css
package.json:
{
"name": "snake-game",
"version": "1.0.0",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "^13.4.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^20.2.5",
"@types/react": "^18.2.7",
"typescript": "^5.0.4"
}
}
tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Dockerfile:
# Use an official Node runtime as a parent image
FROM node:18-alpine
# Set working directory in the container
WORKDIR /app
# Copy package.json and package-lock.json
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy the rest of the application code
COPY . .
# Build the Next.js application
RUN npm run build
# Expose the port the app runs on
EXPOSE 8085
# Start the application
CMD ["npm", "run", "start", "-p", "8085"]
docker-compose.yml:
version: '3.8'
services:
snake-game:
build: .
ports:
- "8085:8085"
volumes:
- .:/app
- /app/node_modules
src/styles/SnakeGame.module.css:
.gameBoard {
width: 400px;
height: 400px;
border: 2px solid black;
position: relative;
}
.snake {
background-color: green;
position: absolute;
}
.food {
background-color: red;
position: absolute;
}
.scorePanel {
display: flex;
justify-content: space-between;
margin-top: 10px;
}
src/components/SnakeGame.tsx:
import React, { useState, useEffect, useCallback } from 'react';
import styles from '../styles/SnakeGame.module.css';
interface SnakeSegment {
x: number;
y: number;
}
const GRID_SIZE = 20;
const CELL_SIZE = 20;
const SnakeGame: React.FC = () => {
const [snake, setSnake] = useState<SnakeSegment[]>([
{ x: 10, y: 10 }
]);
const [food, setFood] = useState<SnakeSegment>({ x: 15, y: 15 });
const [direction, setDirection] = useState<'UP' | 'DOWN' | 'LEFT' | 'RIGHT'>('RIGHT');
const [score, setScore] = useState(0);
const [lives, setLives] = useState(3);
const [gameOver, setGameOver] = useState(false);
const generateFood = useCallback(() => {
return {
x: Math.floor(Math.random() * GRID_SIZE),
y: Math.floor(Math.random() * GRID_SIZE)
};
}, []);
const moveSnake = useCallback(() => {
if (gameOver) return;
const newSnake = [...snake];
const head = { ...newSnake[0] };
switch (direction) {
case 'UP': head.y--; break;
case 'DOWN': head.y++; break;
case 'LEFT': head.x--; break;
case 'RIGHT': head.x++; break;
}
// Check wall collision
if (head.x < 0 || head.x >= GRID_SIZE || head.y < 0 || head.y >= GRID_SIZE) {
handleCollision();
return;
}
// Check self collision
if (newSnake.some(segment => segment.x === head.x && segment.y === head.y)) {
handleCollision();
return;
}
newSnake.unshift(head);
// Check food collision
if (head.x === food.x && head.y === food.y) {
setScore(prev => prev + 1);
setFood(generateFood());
} else {
newSnake.pop();
}
setSnake(newSnake);
}, [snake, direction, food, gameOver]);
const handleCollision = () => {
setLives(prev => {
if (prev <= 1) {
setGameOver(true);
return 0;
}
return prev - 1;
});
// Reset snake position
setSnake([{ x: 10, y: 10 }]);
setDirection('RIGHT');
};
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
switch (e.key) {
case 'ArrowUp':
if (direction !== 'DOWN') setDirection('UP');
break;
case 'ArrowDown':
if (direction !== 'UP') setDirection('DOWN');
break;
case 'ArrowLeft':
if (direction !== 'RIGHT') setDirection('LEFT');
break;
case 'ArrowRight':
if (direction !== 'LEFT') setDirection('RIGHT');
break;
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [direction]);
useEffect(() => {
const gameLoop = setInterval(moveSnake, 200);
return () => clearInterval(gameLoop);
}, [moveSnake]);
const restartGame = () => {
setSnake([{ x: 10, y: 10 }]);
setFood(generateFood());
setDirection('RIGHT');
setScore(0);
setLives(3);
setGameOver(false);
};
return (
<div>
<div className={styles.scorePanel}>
<div>Score: {score}</div>
<div>Lives: {lives}</div>
</div>
{gameOver && (
<div>
Game Over!
<button onClick={restartGame}>Restart</button>
</div>
)}
<div
className={styles.gameBoard}
style={{
width: `${GRID_SIZE * CELL_SIZE}px`,
height: `${GRID_SIZE * CELL_SIZE}px`
}}
>
{snake.map((segment, index) => (
<div
key={index}
className={styles.snake}
style={{
left: `${segment.x * CELL_SIZE}px`,
top: `${segment.y * CELL_SIZE}px`,
width: `${CELL_SIZE}px`,
height: `${CELL_SIZE}px`
}}
/>
))}
<div
className={styles.food}
style={{
left: `${food.x * CELL_SIZE}px`,
top: `${food.y * CELL_SIZE}px`,
width: `${CELL_SIZE}px`,
height: `${CELL_SIZE}px`
}}
/>
</div>
</div>
);
};
export default SnakeGame;
src/pages/index.tsx:
import React from 'react';
import SnakeGame from '../components/SnakeGame';
const Home: React.FC = () => {
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<SnakeGame />
</div>
);
};
export default Home;
next.config.js:
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = nextConfig
To run the project:
- Install Docker and Docker Compose
- Navigate to the project directory
- Run
docker-compose up --build
- Open
http://localhost:8085 in your browser
Game Features:
- Snake moves with arrow keys
- Score increases when eating food
- 3 lives before game over
- Restart option after game over
- Responsive grid-based game
- Dockerized and exposed on port 8085
This implementation provides a complete Snake game with TypeScript, React, Next.js, and Docker. The game includes score tracking, lives, collision detection, and a restart mechanism.
Would you like me to elaborate on any specific part of the implementation?