UNPKG

advanced-games-library

Version:

Advanced Gaming Library for React Native - Four Complete Games with iOS Compatibility Fixes

628 lines (515 loc) โ€ข 15.9 kB
# ๐ŸŽฎ 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!*