Here's a Snake game in React with TypeScript, Next.js, containerized in Docker and exposed on port 8085:
First, let's create the project structure:
mkdir snake-game
cd snake-game
npx create-next-app@latest . --typescript
Now, let's create the game components:
components/SnakeGame.tsx:
import React, { useState, useEffect, useCallback } from 'react';
import styles from '../styles/SnakeGame.module.css';
type Direction = 'UP' | 'DOWN' | 'LEFT' | 'RIGHT';
type Position = { x: number; y: number };
const GRID_SIZE = 20;
const GAME_SPEED = 150;
const INITIAL_SNAKE = [{ x: 10, y: 10 }];
const INITIAL_FOOD = { x: 5, y: 5 };
const INITIAL_LIVES = 3;
const SnakeGame: React.FC = () => {
const [snake, setSnake] = useState<Position[]>(INITIAL_SNAKE);
const [food, setFood] = useState<Position>(INITIAL_FOOD);
const [direction, setDirection] = useState<Direction>('RIGHT');
const [gameOver, setGameOver] = useState<boolean>(false);
const [score, setScore] = useState<number>(0);
const [lives, setLives] = useState<number>(INITIAL_LIVES);
const [isPaused, setIsPaused] = useState<boolean>(false);
const generateFood = useCallback((): Position => {
const newFood = {
x: Math.floor(Math.random() * GRID_SIZE),
y: Math.floor(Math.random() * GRID_SIZE),
};
// Make sure food doesn't spawn on snake
if (snake.some(segment => segment.x === newFood.x && segment.y === newFood.y)) {
return generateFood();
}
return newFood;
}, [snake]);
const resetGame = useCallback(() => {
setSnake(INITIAL_SNAKE);
setFood(generateFood());
setDirection('RIGHT');
setGameOver(false);
setScore(0);
setLives(INITIAL_LIVES);
setIsPaused(false);
}, [generateFood]);
const handleKeyDown = useCallback((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;
case ' ':
setIsPaused(prev => !prev);
break;
case 'r':
resetGame();
break;
}
}, [direction, resetGame]);
useEffect(() => {
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleKeyDown]);
useEffect(() => {
if (gameOver || isPaused) return;
const moveSnake = () => {
setSnake(prevSnake => {
const head = { ...prevSnake[0] };
switch (direction) {
case 'UP':
head.y -= 1;
break;
case 'DOWN':
head.y += 1;
break;
case 'LEFT':
head.x -= 1;
break;
case 'RIGHT':
head.x += 1;
break;
}
// Check if snake hit the wall
if (
head.x < 0 ||
head.x >= GRID_SIZE ||
head.y < 0 ||
head.y >= GRID_SIZE ||
// Check if snake hit itself
prevSnake.some(segment => segment.x === head.x && segment.y === head.y)
) {
if (lives > 1) {
setLives(prev => prev - 1);
return INITIAL_SNAKE;
} else {
setGameOver(true);
return prevSnake;
}
}
const newSnake = [head, ...prevSnake];
// Check if snake ate food
if (head.x === food.x && head.y === food.y) {
setScore(prev => prev + 10);
setFood(generateFood());
} else {
newSnake.pop();
}
return newSnake;
});
};
const gameInterval = setInterval(moveSnake, GAME_SPEED);
return () => clearInterval(gameInterval);
}, [direction, food, gameOver, generateFood, isPaused, lives]);
return (
<div className={styles.gameContainer}>
<div className={styles.header}>
<div className={styles.score}>Score: {score}</div>
<div className={styles.lives}>Lives: {lives}</div>
</div>
<div
className={styles.gameBoard}
style={{
gridTemplateColumns: `repeat(${GRID_SIZE}, 1fr)`,
gridTemplateRows: `repeat(${GRID_SIZE}, 1fr)`
}}
>
{Array.from({ length: GRID_SIZE * GRID_SIZE }).map((_, index) => {
const x = index % GRID_SIZE;
const y = Math.floor(index / GRID_SIZE);
const isSnake = snake.some(segment => segment.x === x && segment.y === y);
const isFood = food.x === x && food.y === y;
return (
<div
key={index}
className={`${styles.cell} ${isSnake ? styles.snake : ''} ${isFood ? styles.food : ''}`}
/>
);
})}
</div>
{gameOver && (
<div className={styles.gameOver}>
<h2>Game Over!</h2>
<p>Your score: {score}</p>
<button onClick={resetGame}>Play Again</button>
</div>
)}
{isPaused && !gameOver && (
<div className={styles.pauseOverlay}>
<h2>Game Paused</h2>
<p>Press Space to continue</p>
</div>
)}
<div className={styles.controls}>
<p>Controls: Arrow keys to move, Space to pause, R to restart</p>
</div>
</div>
);
};
export default SnakeGame;
Now, let's create the CSS module:
styles/SnakeGame.module.css:
.gameContainer {
display: flex;
flex-direction: column;
align-items: center;
margin: 20px auto;
max-width: 600px;
}
.header {
display: flex;
justify-content: space-between;
width: 100%;
margin-bottom: 10px;
}
.score, .lives {
font-size: 1.5rem;
font-weight: bold;
}
.gameBoard {
display: grid;
width: 500px;
height: 500px;
border: 2px solid #333;
background-color: #f0f0f0;
position: relative;
}
.cell {
border: 1px solid #ddd;
}
.snake {
background-color: #4CAF50;
border-radius: 4px;
}
.food {
background-color: #FF5722;
border-radius: 50%;
}
.gameOver, .pauseOverlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: rgba(0, 0, 0, 0.7);
color: white;
z-index: 10;
}
.gameOver button {
margin-top: 20px;
padding: 10px 20px;
font-size: 1rem;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.gameOver button:hover {
background-color: #45a049;
}
.controls {
margin-top: 20px;
text-align: center;
}
Now, let's update the main page:
pages/index.tsx:
import type { NextPage } from 'next';
import Head from 'next/head';
import SnakeGame from '../components/SnakeGame';
import styles from '../styles/Home.module.css';
const Home: NextPage = () => {
return (
<div className={styles.container}>
<Head>
<title>Snake Game</title>
<meta name="description" content="Snake game built with Next.js and TypeScript" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>Snake Game</h1>
<SnakeGame />
</main>
</div>
);
};
export default Home;
Now, let's create a Dockerfile:
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM node:18-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
EXPOSE 8085
CMD ["npm", "start", "--", "-p", "8085"]
Finally, let's create a docker-compose.yml file for easier deployment:
version: '3'
services:
snake-game:
build:
context: .
dockerfile: Dockerfile
ports:
- "8085:8085"
restart: unless-stopped
To run the game:
- Build and start the Docker container:
docker-compose up -d
- Access the game in your browser at http://localhost:8085
Would you like me to explain or break down any part of this code?