Skip to content

dlamersba/test

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

1 Commit
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿšข Multiplayer Battleship Game

A production-ready, real-time multiplayer Battleship game built with Node.js, Express, Socket.IO, and PostgreSQL.

๐ŸŽฏ Features

  • 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

๐Ÿ—๏ธ Architecture

Backend

  • 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

Frontend

  • Vanilla JavaScript with Socket.IO client
  • CSS Grid for game board layout
  • Web Audio API for sound effects
  • Responsive design with CSS media queries

Infrastructure

  • Docker and Docker Compose for containerization
  • Nginx for load balancing and SSL termination
  • Health checks and monitoring
  • Automated testing with Jest

๐Ÿš€ Deployment Options

Option 1: Development (Single Instance)

Use docker-compose.yml for development or testing:

docker-compose up -d
  • Single app instance
  • Direct port binding (3000)
  • Simpler setup

Option 2: Production (Load Balanced)

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

๐Ÿš€ Quick Start

Prerequisites

  • Node.js 18+
  • PostgreSQL 12+
  • Docker and Docker Compose (for containerized deployment)

Development Setup

  1. Clone the repository

    git clone <repository-url>
    cd battleship-multiplayer
  2. Install dependencies

    npm install
  3. Set up environment variables

    cp .env.example .env
    # Edit .env with your configuration
  4. Set up the database

    # Create PostgreSQL database
    createdb battleship_dev
    
    # Run migrations
    npm run migrate
    
    # Seed with sample data (optional)
    npm run seed
  5. Start the development server

    npm run dev
  6. Open your browser Navigate to http://localhost:3000

Production Deployment with Docker

  1. Clone and configure

    git clone <repository-url>
    cd battleship-multiplayer
    cp .env.example .env
    # Edit .env with production values
  2. Generate SSL certificates

    mkdir ssl
    # Add your SSL certificate files:
    # ssl/cert.pem
    # ssl/key.pem
  3. 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
  4. 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

๐Ÿ“‹ Environment Variables

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

๐ŸŽฎ How to Play

Game Modes

  1. 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
  2. vs Computer: Play against AI opponents

    • Choose from 4 difficulty levels
    • Each level uses different targeting strategies

Game Flow

  1. Authentication: Enter your player name
  2. Ship Placement: Place your 5 ships on the grid
    • Carrier (5 cells)
    • Battleship (4 cells)
    • Cruiser (3 cells)
    • Submarine (3 cells)
    • Destroyer (2 cells)
  3. Battle: Take turns attacking enemy waters
  4. Victory: First player to sink all enemy ships wins!

Controls

  • 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

๐Ÿงช Testing

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:watch

๐Ÿ“Š API Documentation

Authentication Endpoints

  • POST /api/auth/login - Player login
  • POST /api/auth/logout - Player logout
  • GET /api/auth/session - Check session status
  • GET /api/auth/validate-name/:name - Validate player name

Game Endpoints

  • GET /api/games/history - Get player's game history
  • POST /api/games/validate-placement - Validate ship placement
  • GET /api/games/meta/difficulties - Get difficulty options

Statistics Endpoints

  • GET /api/stats/player - Get current player stats
  • GET /api/stats/leaderboard - Get top players
  • GET /api/stats/search?q=name - Search players

WebSocket Events

Client to Server

  • authenticate - Authenticate player
  • createGame - Create new game
  • joinGame - Join existing game
  • placeShips - Submit ship placement
  • attack - Attack enemy cell
  • leaveGame - Leave current game

Server to Client

  • authenticated - Authentication successful
  • gameCreated - Game created successfully
  • gameStarted - Game battle phase started
  • attackResult - Attack result
  • gameEnded - Game finished
  • error - Error message

๐Ÿ”ง Configuration

Database Configuration

The application uses PostgreSQL with the following tables:

  • players: Player accounts and statistics
  • games: Game records and state
  • game_moves: Individual move history (optional)

AI Difficulty Levels

  1. Easy: Random targeting
  2. Normal: Basic hunt mode after hits
  3. Hard: Directional hunting and parity targeting
  4. Expert: Probability-based targeting with ship density analysis

Performance Tuning

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

๐Ÿ“ˆ Monitoring and Logging

Logging

The application uses Winston for structured logging:

  • Error logs: logs/error.log
  • Combined logs: logs/combined.log
  • Console output: Development mode

Health Checks

  • HTTP endpoint: GET /health
  • Docker health check: Built into container
  • Database connectivity monitoring

Metrics

Monitor these key metrics:

  • Active game sessions
  • Player connection count
  • Database query performance
  • Memory and CPU usage
  • WebSocket connection stability

๐Ÿš€ Deployment

Docker Deployment

  1. Single Container

    docker build -t battleship .
    docker run -p 3000:3000 battleship
  2. Docker Compose (Recommended)

    docker-compose up -d

Cloud Deployment

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

Scaling

For high traffic:

  1. Run multiple app instances behind a load balancer
  2. Use Redis for shared session storage
  3. Configure database connection pooling
  4. Enable nginx caching
  5. Consider WebSocket sticky sessions

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run the test suite
  6. Submit a pull request

๐Ÿ“ License

MIT License - see LICENSE file for details

๐Ÿ› Troubleshooting

Common Issues

  1. Database Connection Error

    • Check PostgreSQL is running
    • Verify connection credentials
    • Ensure database exists
  2. WebSocket Connection Failed

    • Check firewall settings
    • Verify Socket.IO configuration
    • Test with different browsers
  3. Session Issues

    • Clear browser cookies
    • Check session secret configuration
    • Verify Redis connection (if using)

Debug Mode

Enable debug logging:

LOG_LEVEL=debug npm start

Support

For 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! ๐Ÿ†

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages