advanced-games-library
Version:
Advanced Gaming Library for React Native - Four Complete Games with iOS Compatibility Fixes
96 lines (83 loc) • 1.93 kB
JavaScript
import { useState, useEffect, useRef } from 'react';
// Hook לניהול מנוע המשחק
export const useGameEngine = () => {
const [gameState, setGameState] = useState({
isActive: false,
score: 0,
level: 1,
duration: 0,
status: 'idle' // idle, playing, paused, ended
});
const timerRef = useRef(null);
const startGame = (config = {}) => {
setGameState(prev => ({
...prev,
isActive: true,
status: 'playing',
score: 0,
level: config.startLevel || 1,
duration: 0
}));
// התחלת טיימר
timerRef.current = setInterval(() => {
setGameState(prev => ({
...prev,
duration: prev.duration + 100
}));
}, 100);
};
const pauseGame = () => {
setGameState(prev => ({ ...prev, status: 'paused' }));
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
const resumeGame = () => {
setGameState(prev => ({ ...prev, status: 'playing' }));
timerRef.current = setInterval(() => {
setGameState(prev => ({
...prev,
duration: prev.duration + 100
}));
}, 100);
};
const endGame = (finalScore = null) => {
setGameState(prev => ({
...prev,
isActive: false,
status: 'ended',
score: finalScore !== null ? finalScore : prev.score
}));
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
const updateScore = (points) => {
setGameState(prev => ({
...prev,
score: prev.score + points
}));
};
const updateLevel = (newLevel) => {
setGameState(prev => ({
...prev,
level: newLevel
}));
};
useEffect(() => {
return () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
}, []);
return {
gameState,
startGame,
pauseGame,
resumeGame,
endGame,
updateScore,
updateLevel
};
};