A production-ready, real-time multiplayer Battleship game built with Node.js, Express, Socket.IO, and PostgreSQL.
- Real-time Multiplayer: Play against other players in real-time using WebSockets
- AI Opponents: Four difficulty levels of computer opponents (Easy, Normal, Hard, Expert)
- Ship Placement: Interactive ship placement with validation
- Game Statistics: Player stats, leaderboards, and game history
- Sound Effects: Immersive audio feedback
- Responsive Design: Works on desktop and mobile devices
- Production Ready: Docker support, load balancing, SSL, monitoring
- Node.js with Express framework
- Socket.IO for real-time WebSocket communication
- PostgreSQL database with Knex.js query builder
- Redis for session storage (optional)
- Winston for logging
- Helmet for security headers
- Rate limiting and input validation
- Vanilla JavaScript with Socket.IO client
- CSS Grid for game board layout
- Web Audio API for sound effects
- Responsive design with CSS media queries
- Docker and Docker Compose for containerization
- Nginx for load balancing and SSL termination
- Health checks and monitoring
- Automated testing with Jest
Use docker-compose.yml for development or testing:
docker-compose up -d- Single app instance
- Direct port binding (3000)
- Simpler setup
Use docker-compose.prod.yml for production with load balancing:
docker-compose -f docker-compose.prod.yml up -d- Multiple app instances (app1, app2)
- Nginx load balancer
- No direct port binding (only through nginx)
- Sticky sessions for WebSocket support
- Node.js 18+
- PostgreSQL 12+
- Docker and Docker Compose (for containerized deployment)
-
Clone the repository
git clone <repository-url> cd battleship-multiplayer
-
Install dependencies
npm install
-
Set up environment variables
cp .env.example .env # Edit .env with your configuration -
Set up the database
# Create PostgreSQL database createdb battleship_dev # Run migrations npm run migrate # Seed with sample data (optional) npm run seed
-
Start the development server
npm run dev
-
Open your browser Navigate to
http://localhost:3000
-
Clone and configure
git clone <repository-url> cd battleship-multiplayer cp .env.example .env # Edit .env with production values
-
Generate SSL certificates
mkdir ssl # Add your SSL certificate files: # ssl/cert.pem # ssl/key.pem
-
Deploy with Docker Compose
For development/single instance:
docker-compose up -d
For production/multiple instances:
docker-compose -f docker-compose.prod.yml up -d
-
Run database migrations
# For single instance docker-compose exec app npm run migrate # For multiple instances docker-compose -f docker-compose.prod.yml exec app1 npm run migrate
The application will be available at https://your-domain.com
| Variable | Description | Default |
|---|---|---|
NODE_ENV |
Environment (development/production) | development |
PORT |
Server port | 3000 |
DB_HOST |
PostgreSQL host | localhost |
DB_PORT |
PostgreSQL port | 5432 |
DB_USER |
Database user | battleship_user |
DB_PASSWORD |
Database password | battleship_password |
DB_NAME |
Database name | battleship_dev |
SESSION_SECRET |
Session encryption key | - |
CLIENT_URL |
Allowed client URL for CORS | * |
LOG_LEVEL |
Logging level | info |
-
Multiplayer: Play against other human players
- Create a game and share the Game ID with a friend
- Or join an existing game using a Game ID
-
vs Computer: Play against AI opponents
- Choose from 4 difficulty levels
- Each level uses different targeting strategies
- Authentication: Enter your player name
- Ship Placement: Place your 5 ships on the grid
- Carrier (5 cells)
- Battleship (4 cells)
- Cruiser (3 cells)
- Submarine (3 cells)
- Destroyer (2 cells)
- Battle: Take turns attacking enemy waters
- Victory: First player to sink all enemy ships wins!
- Ship Placement: Click on grid cells to place ships
- Rotate Ship: Use the "Rotate Ship" button to change orientation
- Random Placement: Auto-place all ships randomly
- Attack: Click on enemy grid to attack
- Sound Toggle: Enable/disable sound effects
Run the test suite:
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watchPOST /api/auth/login- Player loginPOST /api/auth/logout- Player logoutGET /api/auth/session- Check session statusGET /api/auth/validate-name/:name- Validate player name
GET /api/games/history- Get player's game historyPOST /api/games/validate-placement- Validate ship placementGET /api/games/meta/difficulties- Get difficulty options
GET /api/stats/player- Get current player statsGET /api/stats/leaderboard- Get top playersGET /api/stats/search?q=name- Search players
authenticate- Authenticate playercreateGame- Create new gamejoinGame- Join existing gameplaceShips- Submit ship placementattack- Attack enemy cellleaveGame- Leave current game
authenticated- Authentication successfulgameCreated- Game created successfullygameStarted- Game battle phase startedattackResult- Attack resultgameEnded- Game finishederror- Error message
The application uses PostgreSQL with the following tables:
- players: Player accounts and statistics
- games: Game records and state
- game_moves: Individual move history (optional)
- Easy: Random targeting
- Normal: Basic hunt mode after hits
- Hard: Directional hunting and parity targeting
- Expert: Probability-based targeting with ship density analysis
For production deployments:
- Enable connection pooling in database configuration
- Use Redis for session storage across multiple instances
- Configure nginx caching for static assets
- Monitor memory usage and optimize garbage collection
- Set up health checks and auto-scaling
The application uses Winston for structured logging:
- Error logs:
logs/error.log - Combined logs:
logs/combined.log - Console output: Development mode
- HTTP endpoint:
GET /health - Docker health check: Built into container
- Database connectivity monitoring
Monitor these key metrics:
- Active game sessions
- Player connection count
- Database query performance
- Memory and CPU usage
- WebSocket connection stability
-
Single Container
docker build -t battleship . docker run -p 3000:3000 battleship -
Docker Compose (Recommended)
docker-compose up -d
The application can be deployed to:
- AWS: ECS, EKS, or Elastic Beanstalk
- Google Cloud: Cloud Run or GKE
- Azure: Container Instances or AKS
- Heroku: With Heroku Postgres add-on
For high traffic:
- Run multiple app instances behind a load balancer
- Use Redis for shared session storage
- Configure database connection pooling
- Enable nginx caching
- Consider WebSocket sticky sessions
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Run the test suite
- Submit a pull request
MIT License - see LICENSE file for details
-
Database Connection Error
- Check PostgreSQL is running
- Verify connection credentials
- Ensure database exists
-
WebSocket Connection Failed
- Check firewall settings
- Verify Socket.IO configuration
- Test with different browsers
-
Session Issues
- Clear browser cookies
- Check session secret configuration
- Verify Redis connection (if using)
Enable debug logging:
LOG_LEVEL=debug npm startFor issues and questions:
- Check existing GitHub issues
- Create a new issue with detailed description
- Include logs and environment details
โ Happy Gaming! May the best admiral win! ๐