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.
- 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)
- 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
- 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
- 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
- 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
- Secure authentication with JWT tokens
- User profiles with game statistics
- Game history tracking and filtering
- Achievement system and badges
- Persistent session management
- 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
Backend (See Backend Repository)
- Node.js + Express REST API
- MongoDB with Mongoose ODM
- Socket.IO for real-time features
- Google Gemini 1.5 Flash for AI analysis
- Vite - Next-generation frontend tooling
- PostCSS - CSS transformation
- ESLint - Code quality and consistency
- TypeScript Compiler - Static type checking
Unlike traditional Tic-Tac-Toe, this implementation introduces temporal strategy through the aging mechanic:
- 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
- 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
- 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
โโโโโโโโโโโโโโโโโโโ
โ React SPA โ
โ (Vite + TS) โ
โ โ
โ โโโโโโโโโโโโโ โ
โ โComponents โ โ REST API
โ โโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ
โ โโโโโโโโโโโโโ โ โ
โ โ Hooks โ โ Socket.IO โผ
โ โโโโโโโโโโโโโ โโโโโโโโโโโโโ โโโโโโโโโโโโโโโ
โ โโโโโโโโโโโโโ โ โ โ Backend โ
โ โReact Queryโ โ โโโโ (Node.js) โ
โ โโโโโโโโโโโโโ โ โโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโ
- 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
- 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)
git clone <repository-url>
cd tic-tac-toe-ainpm installCreate 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 URLnpm run devThe application will run on http://localhost:5173
Note: Make sure the backend server is running before starting the frontend.
# Create production build
npm run build
# Preview production build
npm run previewsrc/
โโโ 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
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
}- Data Preparation: Controller gathers game metadata, all moves, and board states
- Aging Context: Computes lifespan, total expirations, avg lifespan, volatility score
- Gemini Prompt: Structured prompt with game context and aging parameters
- AI Processing: Gemini analyzes each move on tactical + longevity dimensions
- Response Parsing: Normalize scores, map positions, format data for frontend
- Caching: React Query caches analysis for 5 minutes
Socket.IO events for game synchronization:
game:join- Player joins a game roomgame:move- Broadcast move to opponentgame:update- Send updated board stategame:end- Notify game completionconnection:status- Monitor online/offline state
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)
Live gameplay showing piece expiration countdown and move history
Post-game analysis with move timeline, color-coded lifespan bars, and performance metrics
Detailed move-by-move breakdown with expiration badges and quality indicators
User profile with game history, win rates, achievements, and performance trends
- ๐ 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
- 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
The frontend communicates with the backend via REST API and WebSocket connections.
The application uses Axios with interceptors for:
- Automatic JWT token attachment
- Request/response logging
- Error handling and retry logic
- Base URL configuration
Real-time game updates via Socket.IO:
game:join- Join game roomgame:move- Broadcast movesgame:update- Receive board stategame:end- Game completionconnection:status- Connection monitoring
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
# Run ESLint
npm run lint
# Format code
npm run format
# Type checking
npm run type-check# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run E2E tests
npm run test:e2e# Build frontend
npm run build
# Build backend
cd tic-tac-toe-bck && npm run buildBuilt with โค๏ธ using React, TypeScript, and Google Gemini AI