advanced-games-library
Version:
Advanced Gaming Library for React Native - Four Complete Games with iOS Compatibility Fixes
628 lines (515 loc) โข 15.9 kB
Markdown
# ๐ฎ Advanced Games Library
[](https://badge.fury.io/js/advanced-games-library)
[](https://opensource.org/licenses/MIT)
[](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!*