Skip to content

ritik1711999/tic-tac-toe-AI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

40 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐ŸŽฎ Tic-Tac-Toe AI with Aging Mechanics

A revolutionary take on the classic game featuring dynamic piece expiration and AI-powered strategic analysis

An advanced Tic-Tac-Toe application that introduces aging game mechanics where pieces expire after a set number of moves, creating a constantly evolving strategic landscape. Powered by Google Gemini 1.5 Flash AI for comprehensive move analysis and real-time multiplayer support.


โœจ Key Features

๐Ÿง  AI-Powered Move Analysis

  • Google Gemini 1.5 Flash integration for intelligent game analysis
  • Dual-dimensional scoring system: Tactical Quality (70%) + Longevity Safety (30%)
  • Post-game analysis with move timeline and performance metrics
  • Strategic reasoning and alternative move suggestions
  • Outcome probability predictions (win/draw/lose percentages)

โณ Aging Game Mechanic

  • Pieces automatically expire after N moves, adding strategic depth
  • Dynamic board state that evolves throughout gameplay
  • Difficulty-based expiration: Easy (7 moves), Medium (5 moves), Hard (4 moves)
  • Visual indicators for piece lifespan and expiration status
  • Risk vs. longevity trade-off decision making

๐ŸŽฏ Multiple Game Modes

  • AI Opponent: Three difficulty levels with adaptive strategies
  • Human vs Human: Local and online multiplayer via Socket.IO
  • Real-time Updates: Live game state synchronization
  • Aging Toggle: Play with or without the aging mechanic

๐Ÿ“Š Comprehensive Analytics

  • Detailed move timeline with quality indicators
  • Color-coded lifespan visualization (green/yellow/red)
  • Expiration badges showing when pieces expire or have expired
  • Performance summary with key moments highlighting
  • Game history with statistics and trends

๐ŸŽจ Modern UI/UX

  • Responsive design optimized for desktop and mobile
  • Tailwind CSS for elegant, consistent styling
  • Real-time connection status indicators
  • Interactive game board with smooth animations
  • Context-aware quick actions menu

๐Ÿ” User Management

  • Secure authentication with JWT tokens
  • User profiles with game statistics
  • Game history tracking and filtering
  • Achievement system and badges
  • Persistent session management

๐Ÿš€ Tech Stack

Frontend

  • React 18 - Modern UI library with hooks
  • TypeScript - Type-safe development
  • Vite - Lightning-fast build tool and dev server
  • TanStack React Query - Powerful server state management
  • React Router - Client-side routing
  • Tailwind CSS - Utility-first CSS framework
  • Socket.IO Client - Real-time bidirectional communication
  • Node.js + Express REST API
  • MongoDB with Mongoose ODM
  • Socket.IO for real-time features
  • Google Gemini 1.5 Flash for AI analysis

Build & Dev Tools

  • Vite - Next-generation frontend tooling
  • PostCSS - CSS transformation
  • ESLint - Code quality and consistency
  • TypeScript Compiler - Static type checking

๐ŸŒŸ What Makes This Special

Unlike traditional Tic-Tac-Toe, this implementation introduces temporal strategy through the aging mechanic:

Strategic Depth

  • Volatility Tracking: Monitor board complexity as pieces approach expiration
  • Dual-Dimensional Scoring: Evaluate moves on both immediate tactical value and long-term survival
  • Risk Management: Balance aggressive plays with piece longevity
  • Dynamic Board State: The game changes as older pieces expire, creating new opportunities

AI Intelligence

  • Gemini analyzes the full game context including aging parameters
  • Identifies critical expiration moments that shift game dynamics
  • Suggests moves that optimize both tactical position and piece lifespan
  • Provides detailed reasoning for each move evaluation

Visual Feedback

  • Color-Coded Timeline: Green (healthy), Yellow (aging), Red (critical/expired)
  • Expiration Badges: "Expires M8", "Expiring Soon", "Expired M6"
  • Strikethrough Styling: Clearly shows expired moves in history
  • Lifespan Indicators: Track how long each piece survived

๐Ÿ—๏ธ Architecture Overview

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   React SPA     โ”‚
โ”‚  (Vite + TS)    โ”‚
โ”‚                 โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
โ”‚  โ”‚Components โ”‚  โ”‚         REST API
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚                   โ”‚
โ”‚  โ”‚  Hooks    โ”‚  โ”‚       Socket.IO   โ–ผ
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚           โ”‚  โ”‚   Backend   โ”‚
โ”‚  โ”‚React Queryโ”‚  โ”‚           โ””โ”€โ”€โ”‚  (Node.js)  โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚              โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Frontend Design Patterns

  • Component Composition: Modular React components with clear responsibilities
  • Custom Hooks: Reusable logic for auth, games, and dashboard (useAuth, useGames, useDashboard)
  • React Query: Server state management with automatic caching and refetching
  • Context API: Socket connection and authentication state
  • Protected Routes: Route-level authentication guards
  • Error Boundaries: Graceful error handling and recovery

๐Ÿ“ฆ Getting Started

Prerequisites

  • Node.js >= 18.0.0
  • npm >= 9.0.0
  • MongoDB >= 6.0 (local or cloud instance)
  • Google Gemini API Key (get it from Google AI Studio)

Installation

1. Clone the Repository

git clone <repository-url>
cd tic-tac-toe-ai

2. Install Dependencies

npm install

3. Configure Environment

Create a .env file in the root directory:

VITE_API_URL=http://localhost:3000/api         # Backend API URL
VITE_SOCKET_URL=http://localhost:3000          # Socket.IO server URL

4. Start Development Server

npm run dev

The application will run on http://localhost:5173

Note: Make sure the backend server is running before starting the frontend.

Building for Production

# Create production build
npm run build

# Preview production build
npm run preview

๐Ÿ“ Project Structure

src/
โ”œโ”€โ”€ components/                # Reusable UI components
โ”‚   โ”œโ”€โ”€ ui/                   # Base UI components (Button, Input, Select, etc.)
โ”‚   โ”‚   โ”œโ”€โ”€ Header.tsx
โ”‚   โ”‚   โ”œโ”€โ”€ GameStatusIndicator.tsx
โ”‚   โ”‚   โ”œโ”€โ”€ BreadcrumbContext.tsx
โ”‚   โ”‚   โ””โ”€โ”€ QuickActionsMenu.tsx
โ”‚   โ”œโ”€โ”€ AppIcon.tsx           # Icon wrapper component
โ”‚   โ”œโ”€โ”€ ConnectionStatus.tsx  # Real-time connection indicator
โ”‚   โ”œโ”€โ”€ ErrorBoundary.tsx     # Error handling wrapper
โ”‚   โ””โ”€โ”€ ProtectedRoute.tsx    # Auth-protected route wrapper
โ”‚
โ”œโ”€โ”€ hooks/                    # Custom React hooks
โ”‚   โ”œโ”€โ”€ useAuth.ts           # Authentication state & actions
โ”‚   โ”œโ”€โ”€ useGames.ts          # Game data & analysis fetching
โ”‚   โ””โ”€โ”€ useDashboard.ts      # Dashboard statistics
โ”‚
โ”œโ”€โ”€ lib/                      # Core utilities
โ”‚   โ”œโ”€โ”€ api/
โ”‚   โ”‚   โ””โ”€โ”€ client.ts        # Axios instance with interceptors
โ”‚   โ””โ”€โ”€ socket/
โ”‚       โ”œโ”€โ”€ SocketContext.tsx # Socket.IO provider
โ”‚       โ””โ”€โ”€ types.ts         # Socket event types
โ”‚
โ”œโ”€โ”€ pages/                    # Route-level page components
โ”‚   โ”œโ”€โ”€ game-board/          # Live gameplay
โ”‚   โ”‚   โ”œโ”€โ”€ index.tsx
โ”‚   โ”‚   โ”œโ”€โ”€ components/      # GameGrid, MoveHistory, GameControls, etc.
โ”‚   โ”‚   โ””โ”€โ”€ GameBoard.css
โ”‚   โ”œโ”€โ”€ game-analysis/       # Post-game AI analysis
โ”‚   โ”‚   โ”œโ”€โ”€ index.tsx
โ”‚   โ”‚   โ”œโ”€โ”€ components/      # MoveTimeline, AnalysisPanel, PerformanceMetrics
โ”‚   โ”‚   โ””โ”€โ”€ gameAnalysis.css
โ”‚   โ”œโ”€โ”€ game-dashboard/      # User dashboard & stats
โ”‚   โ”‚   โ”œโ”€โ”€ index.tsx
โ”‚   โ”‚   โ”œโ”€โ”€ components/      # StatisticsPanel, RecentGamesList, etc.
โ”‚   โ”‚   โ””โ”€โ”€ gameDashboard.css
โ”‚   โ”œโ”€โ”€ game-history/        # Game history with filters
โ”‚   โ”œโ”€โ”€ login/               # Authentication
โ”‚   โ””โ”€โ”€ register/            # User registration
โ”‚
โ”œโ”€โ”€ store/                    # Client-side state
โ”‚   โ””โ”€โ”€ authStore.ts         # Zustand auth store
โ”‚
โ”œโ”€โ”€ styles/                   # Global styles
โ”‚   โ”œโ”€โ”€ index.css            # Global CSS
โ”‚   โ””โ”€โ”€ tailwind.css         # Tailwind imports
โ”‚
โ”œโ”€โ”€ utils/
โ”‚   โ””โ”€โ”€ cn.ts                # Class name utility
โ”‚
โ”œโ”€โ”€ App.tsx                   # Root component
โ”œโ”€โ”€ Routes.tsx               # Route configuration
โ””โ”€โ”€ index.tsx                # Application entry point

๐ŸŽฏ Key Features Deep Dive

1. Aging Mechanic Implementation

Each move in an aging game receives an expiresOnMove value based on difficulty:

  • Easy: currentMove + 7
  • Medium: currentMove + 5
  • Hard: currentMove + 4

When a move's expiration is reached, it's marked with expiredOnMove and removed from the board. The backend tracks this in the Move model:

{
  moveNumber: 5,
  position: 4,
  player: "X",
  expiresOnMove: 10,    // Will expire on move 10
  expiredOnMove: null,  // Not yet expired
  expiredAt: null
}

2. AI Analysis Workflow

  1. Data Preparation: Controller gathers game metadata, all moves, and board states
  2. Aging Context: Computes lifespan, total expirations, avg lifespan, volatility score
  3. Gemini Prompt: Structured prompt with game context and aging parameters
  4. AI Processing: Gemini analyzes each move on tactical + longevity dimensions
  5. Response Parsing: Normalize scores, map positions, format data for frontend
  6. Caching: React Query caches analysis for 5 minutes

3. Real-time Multiplayer

Socket.IO events for game synchronization:

  • game:join - Player joins a game room
  • game:move - Broadcast move to opponent
  • game:update - Send updated board state
  • game:end - Notify game completion
  • connection:status - Monitor online/offline state

4. Move Quality Scoring

Gemini evaluates moves using a custom prompt that considers:

  • Tactical Value: Winning potential, blocking opponent, strategic positioning
  • Longevity Safety: Likelihood of surviving until game end, risk of expiration
  • Blended Score: 0.7 ร— tactical + 0.3 ร— longevity
  • Quality Label: Excellent (90-100), Good (70-89), Suboptimal (50-69), Mistake (0-49)

๐Ÿ“ธ Screenshots & Demo

Game Board with Aging Indicators

Live gameplay showing piece expiration countdown and move history

AI Analysis Dashboard

Post-game analysis with move timeline, color-coded lifespan bars, and performance metrics

Move Timeline Visualization

Detailed move-by-move breakdown with expiration badges and quality indicators

Statistics Dashboard

User profile with game history, win rates, achievements, and performance trends


๐Ÿ”ฎ Future Enhancements

Planned Features

  • ๐Ÿ† Tournament Mode: Organize multi-player tournaments with brackets
  • ๐Ÿ“ˆ ELO Rating System: Competitive ranking based on win/loss history
  • ๐Ÿค– Multiple AI Models: Support for GPT-4, Claude, or custom models
  • ๐ŸŽฅ Game Replay: Animated replay with analysis overlay
  • ๐Ÿ“ฑ Mobile App: Native iOS/Android versions with React Native
  • ๐ŸŒ Internationalization: Multi-language support
  • ๐ŸŽจ Themes: Dark mode and customizable color schemes
  • ๐Ÿ“Š Advanced Analytics: Heatmaps, opening patterns, endgame statistics
  • ๐Ÿ‘ฅ Social Features: Friend system, spectator mode, chat
  • ๐Ÿ… Achievements: Unlock badges for milestones and special moves

Technical Improvements

  • Implement Redis for session management and caching
  • Add GraphQL API option for flexible data fetching
  • Integrate WebRTC for peer-to-peer multiplayer
  • Implement progressive web app (PWA) features
  • Add comprehensive unit and E2E testing
  • Set up CI/CD pipeline with GitHub Actions
  • Optimize bundle size with code splitting and lazy loading

๐Ÿ“š API Integration

The frontend communicates with the backend via REST API and WebSocket connections.

API Client Setup

The application uses Axios with interceptors for:

  • Automatic JWT token attachment
  • Request/response logging
  • Error handling and retry logic
  • Base URL configuration

Socket.IO Events

Real-time game updates via Socket.IO:

  • game:join - Join game room
  • game:move - Broadcast moves
  • game:update - Receive board state
  • game:end - Game completion
  • connection:status - Connection monitoring

Data Fetching with React Query

The app uses TanStack React Query for:

  • Automatic caching (5-minute default)
  • Background refetching
  • Optimistic updates
  • Loading and error states

For detailed API documentation, see the Backend Repository


๐Ÿ› ๏ธ Development

Code Quality

# Run ESLint
npm run lint

# Format code
npm run format

# Type checking
npm run type-check

Testing

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run E2E tests
npm run test:e2e

Building

# Build frontend
npm run build

# Build backend
cd tic-tac-toe-bck && npm run build

Built with โค๏ธ using React, TypeScript, and Google Gemini AI

About

Frontend client for a rule-driven strategy system inspired by chess.com-style analysis. Visualizes time-bound game state, move expiration, and post-game insights in real time.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages