# 🎮 Advanced Games Library

[![npm version](https://badge.fury.io/js/advanced-games-library.svg)](https://badge.fury.io/js/advanced-games-library)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)

> **A comprehensive React Native games library with advanced performance monitoring, intelligent memory management, error recovery, and multiplayer capabilities.**

## 🚀 Features

- 🎯 **Multiple Game Types** - Puzzle, Memory, Quiz, and Reaction games
- 📊 **Performance Monitoring** - Real-time FPS, memory, and latency tracking
- 🧠 **Smart Memory Management** - Automatic optimization and leak detection
- 🛡️ **Error Recovery** - Graceful error handling with automatic recovery
- 💾 **Intelligent Caching** - Smart data caching with compression
- 🎨 **Beautiful UI Components** - Pre-built game components
- 📱 **React Native Optimized** - Built specifically for mobile performance
- 🔧 **TypeScript Support** - Full type safety and IntelliSense

## 📦 Installation

```bash
npm install advanced-games-library

# iOS (additional step)
cd ios && pod install
```

## 🎮 Quick Start

### Using Game Components in Other Projects

The library provides ready-to-use React components that can be easily integrated into any React Native project.

#### Method 1: Import from main library (Recommended)

```javascript
import React from 'react';
import { 
  SimplePuzzleGameComponent,
  DemoGameComponent,
  MemoryMatchGame,
  ReactionTimeGame,
  GameContainer,
  GameHeader,
  GameModal
} from 'advanced-games-library';
```

#### Method 2: Import from components subpath

```javascript
import React from 'react';
import { 
  SimplePuzzleGameComponent,
  DemoGameComponent,
  MemoryMatchGame,
  ReactionTimeGame
} from 'advanced-games-library/components';
```

#### Method 3: Check component availability

```javascript
import { isComponentAvailable, getAvailableComponents } from 'advanced-games-library/components';

// Check if a specific component is available
if (isComponentAvailable('SimplePuzzleGameComponent')) {
  // Component is ready to use
}

// Get all available components
const availableComponents = getAvailableComponents();
console.log('Available components:', availableComponents);
```

## 🔧 Integration Examples

### Basic Integration

```javascript
// Use games as simple React components
const App = () => {
  return (
    <SimplePuzzleGameComponent
      gridSize={3}
      difficulty="easy"
      onGameComplete={(result) => {
        console.log('🎉 Game completed!', result);
      }}
      onGameStart={() => {
        console.log('🚀 Game started!');
      }}
      showMenu={true}
      autoStart={false}
    />
  );
};
```

### Advanced Integration with Navigation

```javascript
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { 
  SimplePuzzleGameComponent, 
  DemoGameComponent,
  GameContainer,
  GameHeader 
} from 'advanced-games-library';

const Stack = createStackNavigator();

const HomeScreen = ({ navigation }) => (
  <GameContainer>
    <GameHeader title="Game Library" />
    <Button 
      title="Play Puzzle Game" 
      onPress={() => navigation.navigate('PuzzleGame')} 
    />
    <Button 
      title="Play Demo Game" 
      onPress={() => navigation.navigate('DemoGame')} 
    />
  </GameContainer>
);

const PuzzleGameScreen = () => (
  <SimplePuzzleGameComponent
    gridSize={4}
    difficulty="medium"
    onGameComplete={(result) => {
      console.log('Puzzle completed:', result);
      // Navigate to results screen
    }}
  />
);

const DemoGameScreen = () => (
  <DemoGameComponent
    config={{ difficulty: 'hard', showTutorial: true }}
    onGameComplete={(result) => {
      console.log('Demo completed:', result);
    }}
  />
);

const App = () => (
  <NavigationContainer>
    <Stack.Navigator>
      <Stack.Screen name="Home" component={HomeScreen} />
      <Stack.Screen name="PuzzleGame" component={PuzzleGameScreen} />
      <Stack.Screen name="DemoGame" component={DemoGameScreen} />
    </Stack.Navigator>
  </NavigationContainer>
);
```

### Integration with State Management

```javascript
import React, { useState, useEffect } from 'react';
import { 
  SimplePuzzleGameComponent,
  GameManager,
  GameUtils 
} from 'advanced-games-library';

const GameWithState = () => {
  const [gameState, setGameState] = useState(null);
  const [playerScore, setPlayerScore] = useState(0);
  const [gameHistory, setGameHistory] = useState([]);

  useEffect(() => {
    // Initialize game manager
    GameManager.getInstance().initialize({
      enableAnalytics: true,
      enablePerformanceMonitoring: true
    });
  }, []);

  const handleGameComplete = (result) => {
    const newScore = playerScore + result.score;
    setPlayerScore(newScore);
    setGameHistory([...gameHistory, result]);
    
    // Save to local storage
    GameUtils.saveToStorage('gameHistory', gameHistory);
  };

  return (
    <SimplePuzzleGameComponent
      gridSize={4}
      difficulty="medium"
      onGameComplete={handleGameComplete}
      onGameStart={() => setGameState('playing')}
      showMenu={true}
    />
  );
};
```

// Memory Match Game
const MemoryGame = () => (
  <MemoryMatchGameComponent
    gridSize={4}
    difficulty="medium"
    onCardFlip={(data) => console.log('🔄 Card flipped:', data)}
    onGameComplete={(result) => console.log('🎉 Memory game completed!', result)}
  />
);

// Reaction Time Game
const ReactionGame = () => (
  <ReactionTimeGameComponent
    difficulty="hard"
    onReaction={(data) => console.log('⚡ Reaction:', data)}
    onGameComplete={(result) => console.log('🎉 Reaction game completed!', result)}
  />
);
```

### Advanced Usage (Legacy)

```javascript
import { GamesLibrary, SimplePuzzleScreen, SimplePuzzleGame } from 'advanced-games-library';

// Initialize the library
const App = () => {
  useEffect(() => {
    GamesLibrary.initialize({
      enablePerformanceMonitoring: true,
      enableAnalytics: true,
      enableErrorRecovery: true
    });
  }, []);

  return <YourApp />;
};

// Use a puzzle game
const GameScreen = () => {
  const gameInstance = new SimplePuzzleGame();
  
  return (
    <SimplePuzzleScreen
      gameInstance={gameInstance}
      gridSize={4}
      difficulty="medium"
      showHints={true}
      enableAnimations={true}
      onGameComplete={(result) => {
        console.log('Score:', result.score, 'Time:', result.time);
      }}
      onGameExit={() => navigation.goBack()}
    />
  );
};
```

## 🎯 Available Components

### 🎮 Game Components

#### 🧩 SimplePuzzleGameComponent
A complete sliding puzzle game with customizable grid sizes and difficulty levels.

```javascript
<SimplePuzzleGameComponent
  gridSize={3}           // 3, 4, or 5
  difficulty="easy"       // "easy", "medium", "hard"
  onGameComplete={(result) => console.log(result)}
  onGameStart={() => console.log('Game started')}
  showMenu={true}        // Show/hide menu
  autoStart={false}      // Auto-start game
/>
```

#### 🎯 DemoGameComponent
A demo game component showcasing the library's capabilities.

```javascript
<DemoGameComponent
  config={{
    difficulty: 'medium',
    showTutorial: true,
    enableSound: true
  }}
  onGameComplete={(result) => console.log(result)}
  onGameStart={() => console.log('Demo game started')}
/>
```

#### 🧠 MemoryMatchGame
A memory matching game with beautiful card animations.

```javascript
<MemoryMatchGame
  gridSize={4}           // 4, 6, or 8
  difficulty="easy"       // "easy", "medium", "hard"
  onCardFlip={(data) => console.log('Card flipped:', data)}
  onGameComplete={(result) => console.log(result)}
  showMenu={true}
  autoStart={false}
/>
```

#### ⚡ ReactionTimeGame
A reaction time testing game with precision timing.

```javascript
<ReactionTimeGame
  difficulty="easy"       // "easy", "medium", "hard"
  onReaction={(data) => console.log('Reaction:', data)}
  onGameComplete={(result) => console.log(result)}
  showMenu={true}
  autoStart={false}
/>
```

### 🎨 UI Components

#### 📦 GameContainer
A container component for wrapping game content with consistent styling.

```javascript
<GameContainer
  style={{ backgroundColor: '#f0f0f0' }}
  padding={20}
  borderRadius={10}
>
  <YourGameComponent />
</GameContainer>
```

#### 📋 GameHeader
A header component with game title, score, and controls.

```javascript
<GameHeader
  title="My Game"
  score={1000}
  onBack={() => navigation.goBack()}
  onMenu={() => setShowMenu(true)}
  showTimer={true}
  time={120}
/>
```

#### 🎭 GameModal
A modal component for game menus, settings, and dialogs.

```javascript
<GameModal
  visible={showMenu}
  onClose={() => setShowMenu(false)}
  title="Game Menu"
  showCloseButton={true}
>
  <Text>Menu content here</Text>
</GameModal>
```

#### 🎪 GameWidgets
A collection of game UI widgets like progress bars and indicators.

```javascript
<GameWidgets
  progress={75}
  level={3}
  achievements={['first_win', 'speed_demon']}
  showProgressBar={true}
  showLevelIndicator={true}
  showAchievements={true}
/>
```

### 🎮 Multiplayer Components

#### 🌐 MultiplayerGameDemo
A demo component showcasing multiplayer game capabilities.

```javascript
<MultiplayerGameDemo
  roomId="game-room-123"
  playerId="player-456"
  onPlayerJoin={(player) => console.log('Player joined:', player)}
  onGameStart={() => console.log('Multiplayer game started')}
  onGameComplete={(result) => console.log('Game completed:', result)}
/>
```

### 📱 Screen Components

#### 🖥️ SimplePuzzleScreen
A complete screen component for the puzzle game with navigation.

```javascript
<SimplePuzzleScreen
  navigation={navigation}
  route={route}
  onGameComplete={(result) => {
    console.log('Game completed:', result);
    navigation.navigate('Results', { result });
  }}
/>
```

#### 🧪 DemoGameTestApp
A test app component for development and testing.

```javascript
<DemoGameTestApp
  config={{
    enableDebug: true,
    showPerformance: true,
    testMode: true
  }}
  onTestComplete={(results) => console.log('Tests completed:', results)}
/>
```
```javascript
<SimplePuzzleGameComponent
  gridSize={3}           // 3, 4, or 5
  difficulty="easy"       // "easy", "medium", "hard"
  onGameComplete={(result) => console.log(result)}
  onGameStart={() => console.log('Game started')}
  showMenu={true}        // Show/hide menu
  autoStart={false}      // Auto-start game
/>
```

**Features:**
- **Grid sizes**: 3x3, 4x4, 5x5
- **Difficulties**: Easy, Medium, Hard
- **Built-in menu**: Choose difficulty and grid size
- **Hints system**: Get help when stuck
- **Progress tracking**: Moves, time, and score

### 🧠 Memory Match Game Component
```javascript
<MemoryMatchGameComponent
  gridSize={4}           // 4, 6, or 8
  difficulty="easy"       // "easy", "medium", "hard"
  onCardFlip={(data) => console.log('Card flipped:', data)}
  onGameComplete={(result) => console.log(result)}
  showMenu={true}
  autoStart={false}
/>
```

**Features:**
- **Grid sizes**: 4x4, 6x6, 8x8
- **Multiple themes** with beautiful graphics
- **Performance tracking** and improvement suggestions
- **Match counting**: Track successful pairs
- **Visual feedback**: Cards change color when matched

### ⚡ Reaction Time Game Component
```javascript
<ReactionTimeGameComponent
  difficulty="easy"       // "easy", "medium", "hard"
  onReaction={(data) => console.log('Reaction:', data)}
  onGameComplete={(result) => console.log(result)}
  showMenu={true}
  autoStart={false}
/>
```

**Features:**
- **Precision timing** with latency measurement
- **Performance analytics** and trends
- **Visual feedback**: Color changes indicate when to react
- **Average reaction time**: Track your performance
- **Multiple rounds**: Test consistency

### Legacy Game Classes
For advanced usage, you can still use the game classes directly:

```javascript
import { SimplePuzzleGame, MemoryMatchGame, ReactionTimeGame } from 'advanced-games-library';

const game = new SimplePuzzleGame();
await game.initialize(config);
await game.start();
```

## 📊 Performance Monitoring

```javascript
import { performanceMonitor, usePerformanceMonitor } from 'advanced-games-library';

// Start monitoring
performanceMonitor.startGameSession('my-game');

// Use in React components
const GameComponent = () => {
  const { performanceData, getPerformanceScore } = usePerformanceMonitor();
  
  return (
    <View>
      <Text>FPS: {performanceData.fps}</Text>
      <Text>Memory: {performanceData.memoryUsage}%</Text>
      <Text>Score: {getPerformanceScore()}%</Text>
    </View>
  );
};
```

## 🧠 Memory Management

```javascript
import { advancedMemoryManager } from 'advanced-games-library';

// Monitor memory status
const memoryStatus = advancedMemoryManager.getCurrentMemoryStatus();

// Auto-optimize when needed
if (memoryStatus.riskLevel === 'high') {
  const result = await advancedMemoryManager.optimizeMemory();
  console.log(`Freed ${result.memoryFreed}MB`);
}
```

## 🛡️ Error Handling

```javascript
import { gameErrorHandler, ErrorCategory, ErrorSeverity } from 'advanced-games-library';

// Set up error handling
gameErrorHandler.onError((error) => {
  if (error.severity === ErrorSeverity.CRITICAL) {
    // Handle critical errors
    showErrorModal(error.message);
  }
});

// Safe async operations
const gameData = await safeAsync(
  () => loadGameFromServer(),
  getDefaultGameData() // fallback
);
```

## 🎨 UI Components

```javascript
import { GameContainer, GameButton, ScoreDisplay, Timer } from 'advanced-games-library';

<GameContainer title="My Game" showHeader={true}>
  <ScoreDisplay currentScore={score} showProgress={true} />
  <Timer timeLeft={timeLeft} showProgress={true} />
  <GameButton title="Start" onPress={startGame} variant="primary" />
</GameContainer>
```

## 🔧 Advanced Configuration

```javascript
await GamesLibrary.initialize({
  enableAnalytics: true,
  enablePerformanceMonitoring: true,
  enableAdvancedMemoryManagement: true,
  enableErrorRecovery: true,
  customization: {
    brandName: 'My Gaming App',
    primaryColor: '#007AFF',
    theme: 'dark' // 'light' | 'dark'
  },
  performance: {
    targetFPS: 60,
    memoryWarningThreshold: 80,
    enableAutoOptimization: true
  }
});
```

## 📱 Platform Support

| Platform | Support | Notes |
|----------|---------|--------|
| iOS | ✅ Full | Requires `pod install` |
| Android | ✅ Full | Works out of the box |
| Web | 🔄 Planned | Coming in v2.0 |

## 📋 Requirements

- **React Native** ≥ 0.60.0
- **React** ≥ 16.8.0
- **iOS** ≥ 11.0
- **Android** ≥ API 21

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md).

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🆘 Support

- **📚 Documentation**: [Full API Reference](docs/api.md)
- **🐛 Issues**: [GitHub Issues](https://github.com/your-username/advanced-games-library/issues)
- **💬 Discussions**: [GitHub Discussions](https://github.com/your-username/advanced-games-library/discussions)
- **📧 Email**: your.email@example.com

## 🎯 Roadmap

- [ ] **v1.1**: Web platform support
- [ ] **v1.2**: More game types (Cards, Board games)
- [ ] **v1.3**: Advanced AI opponents
- [ ] **v2.0**: 3D games support

---

**Made with ❤️ for the React Native community**

*Star ⭐ this repo if you find it helpful!*
