import React, { useState, useEffect, useCallback } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Alert, SafeAreaView, StatusBar, Dimensions, } from 'react-native'; import { MemoryMatchGame as GameClass } from './index'; import { GameDifficulty } from '../../core/types'; const { width: screenWidth } = Dimensions.get('window'); interface MemoryMatchGameProps { gridSize?: number; difficulty?: 'easy' | 'medium' | 'hard' | 'expert'; onGameComplete?: (result: any) => void; onGameStart?: () => void; onCardFlip?: (cardData: any) => void; showMenu?: boolean; autoStart?: boolean; title?: string; subtitle?: string; showStats?: boolean; enableHints?: boolean; enableReset?: boolean; theme?: { primaryColor?: string; secondaryColor?: string; backgroundColor?: string; textColor?: string; cardColor?: string; matchedColor?: string; }; } export const MemoryMatchGameComponent: React.FC = ({ gridSize = 4, difficulty = 'easy', onGameComplete, onGameStart, onCardFlip, showMenu = true, autoStart = false, title = '🧠 משחק זיכרון', subtitle = 'מצא את הזוגות התואמים!', showStats = true, enableHints = true, enableReset = true, theme = { primaryColor: '#3498db', secondaryColor: '#2ecc71', backgroundColor: '#f8f9fa', textColor: '#2c3e50', cardColor: '#ffffff', matchedColor: '#27ae60' } }) => { const [currentScreen, setCurrentScreen] = useState(showMenu ? 'menu' : 'game'); const [gameInstance, setGameInstance] = useState(null); const [gameState, setGameState] = useState(null); const [isLoading, setIsLoading] = useState(false); const [gameStats, setGameStats] = useState({ matches: 0, attempts: 0, time: 0, isComplete: false, }); const [internalStats, setInternalStats] = useState({ totalGames: 0, bestScore: 0, bestTime: 0, totalMatches: 0, averageAttempts: 0, }); useEffect(() => { if (autoStart && !showMenu) { startGame(); } }, [autoStart, showMenu]); const startGame = async () => { setIsLoading(true); try { if (!GameClass) { console.error('❌ GameClass is undefined!'); Alert.alert('שגיאה', 'מחלקת המשחק לא נטענה מהספרייה'); setIsLoading(false); return; } const game = new GameClass(); let gameDifficulty: GameDifficulty; switch (difficulty) { case 'easy': gameDifficulty = GameDifficulty.EASY; break; case 'medium': gameDifficulty = GameDifficulty.MEDIUM; break; case 'hard': gameDifficulty = GameDifficulty.HARD; break; case 'expert': gameDifficulty = GameDifficulty.EXPERT; break; default: gameDifficulty = GameDifficulty.EASY; } await game.initialize({ gameId: 'memory-match', gridSize, difficulty: gameDifficulty, customization: { theme: { name: 'default', colors: { primary: theme.primaryColor, secondary: theme.secondaryColor, background: theme.backgroundColor, text: theme.textColor, card: theme.cardColor, matched: theme.matchedColor, }, }, }, rules: {} } as any); (game as any).on('cardFlip', (cardData: any) => { console.log('🔄 Card flipped:', cardData); updateGameStats(game); onCardFlip?.(cardData); }); (game as any).on('gameComplete', (result: any) => { console.log('🏁 Memory game complete!', result); const newTotalGames = internalStats.totalGames + 1; const newTotalMatches = internalStats.totalMatches + result.customData?.matches || 0; const newAverageAttempts = Math.round((internalStats.averageAttempts * (newTotalGames - 1) + result.customData?.attempts) / newTotalGames); setInternalStats(prev => ({ totalGames: newTotalGames, bestScore: Math.max(prev.bestScore, result.score || 0), bestTime: prev.bestTime === 0 ? result.timeSpent : Math.min(prev.bestTime, result.timeSpent || 0), totalMatches: newTotalMatches, averageAttempts: newAverageAttempts, })); onGameComplete?.(result); if (showMenu) { Alert.alert( '🎉 כל הכבוד!', `השלמת את משחק הזיכרון!\n` + `זוגות שנמצאו: ${result.customData?.matches || 0}\n` + `ניסיונות: ${result.customData?.attempts || 0}\n` + `זמן: ${Math.floor(result.timeSpent / 1000)}s\n` + `ניקוד: ${result.score}`, [ { text: 'משחק חדש', onPress: () => startGame() }, { text: 'חזור לתפריט', onPress: () => setCurrentScreen('menu') }, ], ); } }); (game as any).on('gameStarted', () => { console.log('🚀 Memory game started!'); onGameStart?.(); }); setGameInstance(game); setGameState(game.getMemoryState()); await game.start(); setIsLoading(false); setCurrentScreen('game'); } catch (error) { console.error('❌ Failed to start memory game:', error); Alert.alert('שגיאה', 'נכשל בהתחלת משחק הזיכרון'); setIsLoading(false); } }; const updateGameStats = (game: any) => { const state = game.getMemoryState(); setGameStats({ matches: state.matches, attempts: state.attempts, time: game.getElapsedTime(), isComplete: state.matches === state.cards.length / 2, }); setGameState(state); }; const handleCardPress = (cardId: string) => { if (!gameInstance || !gameState) return; gameInstance.processPlayerAction({ type: 'FLIP_CARD', payload: { cardId } }); updateGameStats(gameInstance); }; const resetGame = () => { if (gameInstance) { gameInstance.restart(); setGameState(gameInstance.getMemoryState()); setGameStats({ matches: 0, attempts: 0, time: 0, isComplete: false, }); } }; const renderCard = (card: any, index: number) => { const cardSize = (screenWidth - 80) / gridSize; const isFlipped = card.isFlipped || card.isMatched; const isMatched = card.isMatched; return ( handleCardPress(card.id)} disabled={isFlipped || gameStats.isComplete} activeOpacity={0.8} > {isFlipped ? ( {card.value} ) : ( ? )} ); }; const renderMemoryBoard = () => ( {gameState?.cards.map((card: any, index: number) => renderCard(card, index))} ); const renderMenuScreen = () => ( {title} {subtitle} {isLoading ? 'טוען...' : 'התחל משחק'} גודל רשת: {gridSize}x{gridSize} רמת קושי: {difficulty} {internalStats.totalGames > 0 && ( <> משחקים קודמים: {internalStats.totalGames} ניקוד הטוב ביותר: {internalStats.bestScore} )} ); const renderGameScreen = () => ( משחק זיכרון {showStats && ( זוגות: {gameStats.matches} ניסיונות: {gameStats.attempts} זמן: {Math.floor(gameStats.time / 1000)}s )} {renderMemoryBoard()} {enableReset && ( אפס משחק )} {showMenu && ( setCurrentScreen('menu')} > חזור לתפריט )} ); return currentScreen === 'menu' ? renderMenuScreen() : renderGameScreen(); }; const styles = StyleSheet.create({ container: { flex: 1, }, menuContent: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20, }, title: { fontSize: 28, fontWeight: 'bold', marginBottom: 10, textAlign: 'center', }, subtitle: { fontSize: 16, marginBottom: 30, textAlign: 'center', opacity: 0.8, }, menuButtons: { width: '100%', marginBottom: 30, }, button: { padding: 15, borderRadius: 10, alignItems: 'center', marginVertical: 5, }, buttonText: { color: 'white', fontSize: 16, fontWeight: 'bold', }, gameInfo: { width: '100%', }, infoText: { fontSize: 14, marginVertical: 2, textAlign: 'center', }, gameContent: { flex: 1, padding: 20, }, header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, }, gameTitle: { fontSize: 24, fontWeight: 'bold', }, stats: { alignItems: 'flex-end', }, statText: { fontSize: 14, marginVertical: 2, }, memoryBoard: { flex: 1, justifyContent: 'center', alignItems: 'center', }, grid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', alignItems: 'center', }, card: { margin: 4, borderRadius: 8, justifyContent: 'center', alignItems: 'center', borderWidth: 2, }, cardValue: { fontSize: 24, fontWeight: 'bold', }, cardBack: { fontSize: 20, fontWeight: 'bold', }, controls: { flexDirection: 'row', justifyContent: 'space-around', marginTop: 20, }, controlButton: { padding: 10, borderRadius: 8, minWidth: 100, alignItems: 'center', }, });