Skip to content
luxmikantPublic

About

Connect 4 is a two-player strategy game in which a player must form a line of four pieces horizontally, vertically, or diagonally.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

ย 

History

47 Commits

Folders and files

NameName
Last commit message
Last commit date
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Connect 4 Multiplayer System

A real-time multiplayer Connect 4 game system built with Go backend, React frontend, and Kafka-based analytics pipeline.

โœจ Key Highlights

๐ŸŽฎ Real-Time Multiplayer - Play live games via WebSocket with instant move synchronization
๐Ÿค– Smart AI Bot - Challenge an intelligent bot using minimax algorithm with alpha-beta pruning
โšก Auto Matchmaking - 10-second queue with automatic bot fallback
๐Ÿ“Š Kafka Analytics - Real-time game metrics and player behavior tracking via Apache Kafka
๐Ÿ† Live Leaderboard - Track rankings, win rates, and player statistics
๐Ÿ”„ Session Persistence - Automatic reconnection with 30-second grace period

Features

  • Real-time multiplayer gameplay via WebSocket connections
  • Intelligent bot opponents using minimax algorithm with alpha-beta pruning
  • Automatic matchmaking with 10-second timeout fallback to bot games
  • Player reconnection support with 30-second session persistence
  • Live leaderboard with player statistics and rankings
  • Kafka-powered analytics - Tracks gameplay metrics, player behavior, game duration, and peak hours

Architecture

  • Go Backend Server: Game logic, WebSocket communication, REST API
  • React Frontend: User interface for gameplay and leaderboard
  • PostgreSQL: Game data and player statistics storage
  • Kafka: Analytics event streaming
  • Redis: Session management and caching

Quick Start

Prerequisites

  • Go 1.21+
  • Node.js 18+
  • Docker & Docker Compose
  • Make (optional, for convenience commands)

Development Setup

  1. Clone the repository

    git clone <repository-url>
    cd connect4-multiplayer
  2. Start the backend services

    Option A: Using Docker (Recommended)

    # Start all services (PostgreSQL, Redis, Kafka, Backend)
    docker-compose up

    Option B: Local Development

    # 1. Start dependencies (PostgreSQL, Redis, Kafka)
    docker-compose up postgres redis kafka
    
    # 2. Run database migrations
    go run cmd/migrate/main.go
    
    # 3. Start the backend server
    go run cmd/server/main.go
    # OR with Make:
    make run-server
    
    # 4. (Optional) Start analytics service
    go run cmd/analytics/main.go

    The server will start on http://localhost:8080 with WebSocket endpoint at ws://localhost:8080/ws

  3. Start the frontend

    cd web
    npm install
    npm run dev

    Frontend will be available at http://localhost:5173

  4. Set up credentials (Choose one option)

    Option A: Interactive Setup (Recommended)

    make setup-credentials

    Option B: Manual Setup

    # Create environment file
    make create-env
    
    # Edit .env with your Supabase and Confluent Cloud credentials
    # See CREDENTIALS_SETUP.md for detailed instructions

    Option C: Local Development Only

    # Use local services (no cloud setup required)
    make docker-up
    # Uses local PostgreSQL, Redis, and Kafka
  5. Validate your setup

    # Test database and Kafka connections
    make test-db
    make test-kafka
  6. Install development tools

    make setup
  7. Run database migrations

    make migrate
  8. Start the development server

    make dev

The server will start at http://localhost:8080 with hot reload enabled.

๐Ÿ“‹ Need help with credentials? See CREDENTIALS_SETUP.md for a quick setup guide or docs/cloud-setup-guide.md for detailed instructions.

Analytics

make run-analytics # Start Kafka analytics consumer


## ๐Ÿ“Š Kafka Analytics

The system includes **real-time analytics** powered by Apache Kafka. Game events are published to Kafka and consumed by an analytics service that tracks:

- **Gameplay Metrics**: Average game duration, games per hour/day, min/max duration
- **Player Metrics**: Unique players per hour, active games, player win rates
- **Event Tracking**: All game events (started, moves, completed) stored for analysis

### Running Analytics Service

```bash
# Build analytics consumer
go build -o analytics.exe ./cmd/analytics

# Run analytics service
./analytics.exe

Viewing Analytics Data

-- View latest analytics snapshot
SELECT 
    timestamp,
    games_completed_hour,
    games_completed_day,
    avg_game_duration_sec,
    unique_players_hour
FROM analytics_snapshots
ORDER BY timestamp DESC
LIMIT 10;

-- Most frequent winners
SELECT username, games_won, win_rate 
FROM player_stats 
ORDER BY games_won DESC 
LIMIT 10;

๐Ÿ“– For detailed analytics guide, see docs/kafka-analytics-guide.md

Project Structure

/
โ”œโ”€โ”€ cmd/                    # Application entry points
โ”‚   โ”œโ”€โ”€ server/            # Game server main
โ”‚   โ”œโ”€โ”€ analytics/         # Analytics service main
โ”‚   โ””โ”€โ”€ migrate/           # Database migration tool
โ”œโ”€โ”€ internal/              # Private application code
โ”‚   โ”œโ”€โ”€ game/             # Game logic and engine
โ”‚   โ”œโ”€โ”€ websocket/        # WebSocket connection management
โ”‚   โ”œโ”€โ”€ bot/              # AI bot implementation
โ”‚   โ”œโ”€โ”€ matchmaking/      # Player matching service
โ”‚   โ”œโ”€โ”€ analytics/        # Analytics event processing
โ”‚   โ””โ”€โ”€ database/         # Database models and operations
โ”œโ”€โ”€ pkg/                   # Public library code
โ”‚   โ”œโ”€โ”€ models/           # Shared data structures
โ”‚   โ””โ”€โ”€ utils/            # Common utilities
โ”œโ”€โ”€ web/                   # Frontend React application
โ”œโ”€โ”€ migrations/            # Database schema migrations
โ””โ”€โ”€ docs/                 # Project documentation

API Documentation

Once the server is running, visit:

  • Swagger UI: http://localhost:8080/swagger/index.html
  • Health Check: http://localhost:8080/health

Configuration

Environment Variables

Variable Description Default
ENVIRONMENT Application environment development
SERVER_PORT Server port 8080
DATABASE_URL PostgreSQL connection string Local PostgreSQL
KAFKA_BOOTSTRAP_SERVERS Kafka brokers localhost:9092
KAFKA_API_KEY Confluent Cloud API key -
KAFKA_API_SECRET Confluent Cloud API secret -
REDIS_URL Redis connection string localhost:6379

Cloud Services Setup

Supabase (Database)

  1. Create a new Supabase project
  2. Get your connection string from Settings > Database
  3. Set DATABASE_URL environment variable

Confluent Cloud (Kafka)

  1. Create a Confluent Cloud account
  2. Create a new cluster
  3. Generate API keys
  4. Set KAFKA_BOOTSTRAP_SERVERS, KAFKA_API_KEY, and KAFKA_API_SECRET

Deployment

๐Ÿš€ Deploy your game for FREE! See our comprehensive deployment guides:

  • DEPLOYMENT.md - Complete step-by-step deployment guide

    • Deploy backend to Render.com (Free tier with WebSocket support)
    • Deploy frontend to Vercel (Free tier with auto-deploy)
    • No shell access needed - Migrations run automatically!
    • Environment variable templates included
    • Troubleshooting guide for common issues
  • DEPLOYMENT_QUICK_REF.md - Quick reference card

    • Environment variables cheat sheet
    • One-page deployment steps
    • Common issues and solutions

Recommended Free Stack

  • Backend: Render.com (Go server + PostgreSQL)
  • Frontend: Vercel (React/Vite)
  • Database: Supabase or Render PostgreSQL
  • Kafka: Confluent Cloud (already configured)

Alternative Options

Railway

# Install Railway CLI
npm install -g @railway/cli

# Login and deploy
railway login
railway init
railway up

Fly.io

# Install flyctl
curl -L https://fly.io/install.sh | sh

# Deploy
fly launch
fly deploy

Testing

Unit Tests

make test

Property-Based Tests

make test-property

Integration Tests

make test-integration

Coverage Report

make test-coverage
open coverage.html

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.

Support

For questions and support, please open an issue on GitHub.

About

Connect 4 is a two-player strategy game in which a player must form a line of four pieces horizontally, vertically, or diagonally.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages