advanced-games-library
Version:
Advanced Gaming Library for React Native - Four Complete Games with iOS Compatibility Fixes
455 lines (404 loc) • 13.1 kB
JavaScript
/**
* Simple Puzzle Game Component
* Version 3.3.0 - Organized Code Structure
*/
// Import React safely
let React;
try {
React = require('react');
console.log('✅ React loaded successfully for SimplePuzzleGame');
} catch (error) {
console.error('❌ Failed to load React:', error);
}
const { View, Text, TouchableOpacity, StyleSheet, Alert, Dimensions } = require('react-native');
const { generatePuzzleTiles, isPuzzleSolved } = require('../utils/helpers');
// ===========================================
// REAL SIMPLE PUZZLE GAME - CLASS COMPONENT!
// ===========================================
class SimplePuzzleGameComponent extends React.Component {
constructor(props) {
super(props);
console.log('🧩 SimplePuzzleGameComponent - REAL GAME initializing...');
const gridSize = props.gridSize || 3;
this.state = {
currentScreen: props.showMenu !== false ? 'menu' : 'game',
tiles: [],
moves: 0,
isComplete: false,
startTime: null,
gameTime: 0,
gridSize: gridSize,
isGameStarted: false,
difficulty: props.difficulty || 'easy'
};
this.initializeGame = this.initializeGame.bind(this);
this.startGame = this.startGame.bind(this);
this.handleTilePress = this.handleTilePress.bind(this);
this.checkGameComplete = this.checkGameComplete.bind(this);
this.resetGame = this.resetGame.bind(this);
this.goToMenu = this.goToMenu.bind(this);
}
initializeGame() {
console.log('🔄 Initializing puzzle game...');
const tiles = generatePuzzleTiles(this.state.gridSize);
this.setState({
tiles: tiles,
moves: 0,
isComplete: false,
startTime: Date.now(),
gameTime: 0,
isGameStarted: true
});
this.timer = setInterval(() => {
if (!this.state.isComplete && this.state.startTime) {
const currentTime = (Date.now() - this.state.startTime) / 1000;
this.setState({ gameTime: currentTime });
}
}, 100);
}
startGame() {
console.log('🚀 Starting puzzle game...');
this.setState({ currentScreen: 'game' });
this.initializeGame();
if (this.props.onGameStart) {
this.props.onGameStart();
}
}
handleTilePress(tileIndex) {
console.log(`🔲 Tile pressed: ${tileIndex}`);
const { tiles, gridSize, isComplete } = this.state;
if (isComplete) return;
const emptyIndex = tiles.indexOf(0);
// Check if tile is adjacent to empty space
const tileRow = Math.floor(tileIndex / gridSize);
const tileCol = tileIndex % gridSize;
const emptyRow = Math.floor(emptyIndex / gridSize);
const emptyCol = emptyIndex % gridSize;
const isAdjacent = (
(Math.abs(tileRow - emptyRow) === 1 && tileCol === emptyCol) ||
(Math.abs(tileCol - emptyCol) === 1 && tileRow === emptyRow)
);
if (isAdjacent) {
// Swap tiles
const newTiles = [...tiles];
[newTiles[tileIndex], newTiles[emptyIndex]] = [newTiles[emptyIndex], newTiles[tileIndex]];
this.setState({
tiles: newTiles,
moves: this.state.moves + 1
}, () => {
this.checkGameComplete();
});
}
}
checkGameComplete() {
if (isPuzzleSolved(this.state.tiles, this.state.gridSize)) {
console.log('🎉 Puzzle game completed!');
if (this.timer) {
clearInterval(this.timer);
}
const finalTime = (Date.now() - this.state.startTime) / 1000;
const baseScore = this.state.gridSize === 3 ? 500 : this.state.gridSize === 4 ? 800 : 1200;
const score = Math.max(baseScore - this.state.moves * 5 - finalTime * 3, 50);
this.setState({
isComplete: true,
gameTime: finalTime
});
const result = {
score: Math.round(score),
moves: this.state.moves,
time: finalTime,
gridSize: this.state.gridSize,
completed: true
};
if (this.props.onGameComplete) {
this.props.onGameComplete(result);
}
setTimeout(() => {
Alert.alert(
'🎉 מעולה!',
`השלמת את הפאזל!\n\n` +
`🔲 גודל: ${this.state.gridSize}x${this.state.gridSize}\n` +
`🕐 זמן: ${finalTime.toFixed(1)} שניות\n` +
`🔄 מהלכים: ${this.state.moves}\n` +
`🎯 ניקוד: ${Math.round(score)}`,
[
{ text: 'פאזל חדש', onPress: this.resetGame },
{ text: 'תפריט', onPress: this.goToMenu }
]
);
}, 500);
}
}
resetGame() {
console.log('🔄 Resetting puzzle game...');
if (this.timer) {
clearInterval(this.timer);
}
this.initializeGame();
}
goToMenu() {
console.log('🏠 Going to puzzle menu...');
if (this.timer) {
clearInterval(this.timer);
}
this.setState({ currentScreen: 'menu' });
}
componentWillUnmount() {
if (this.timer) {
clearInterval(this.timer);
}
}
renderTile(tile, index) {
const styles = this.getPuzzleStyles();
const isEmpty = tile === 0;
return React.createElement(TouchableOpacity, {
key: index,
style: [styles.tile, isEmpty && styles.emptyTile],
onPress: () => this.handleTilePress(index),
disabled: isEmpty,
activeOpacity: 0.7
},
!isEmpty && React.createElement(Text, { style: styles.tileText }, tile.toString())
);
}
renderMenu() {
const styles = this.getPuzzleStyles();
const { gridSize, difficulty } = this.state;
return React.createElement(View, { style: styles.menuContainer },
React.createElement(Text, { style: styles.title }, '🧩 משחק פאזל'),
React.createElement(Text, { style: styles.subtitle }, 'סדרו את המספרים בסדר הנכון!'),
React.createElement(View, { style: styles.gameInfo },
React.createElement(Text, { style: styles.infoText }, `🔲 גודל: ${gridSize}x${gridSize}`),
React.createElement(Text, { style: styles.infoText }, `⚙️ רמה: ${difficulty}`),
React.createElement(Text, { style: styles.infoText }, `🎯 מטרה: סדר 1-${gridSize * gridSize - 1}`)
),
React.createElement(TouchableOpacity,
{ style: styles.startButton, onPress: this.startGame },
React.createElement(Text, { style: styles.buttonText }, '🚀 התחל פאזל')
)
);
}
renderGame() {
const styles = this.getPuzzleStyles();
const { tiles, moves, gridSize, gameTime, isComplete } = this.state;
return React.createElement(View, { style: styles.gameContainer },
React.createElement(View, { style: styles.header },
React.createElement(Text, { style: styles.gameTitle }, '🧩 משחק פאזל'),
React.createElement(View, { style: styles.stats },
React.createElement(Text, { style: styles.statText }, `גודל: ${gridSize}x${gridSize}`),
React.createElement(Text, { style: styles.statText }, `מהלכים: ${moves}`),
React.createElement(Text, { style: styles.statText }, `זמן: ${gameTime.toFixed(1)}s`)
)
),
React.createElement(View, { style: styles.puzzleBoard },
...this.renderPuzzleGrid()
),
isComplete && React.createElement(View, { style: styles.completeIndicator },
React.createElement(Text, { style: styles.completeText }, '🎉 פוזל הושלם!')
),
React.createElement(View, { style: styles.controls },
React.createElement(TouchableOpacity,
{ style: styles.controlButton, onPress: this.resetGame },
React.createElement(Text, { style: styles.controlButtonText }, '🔄 פאזל חדש')
),
React.createElement(TouchableOpacity,
{ style: [styles.controlButton, styles.menuButton], onPress: this.goToMenu },
React.createElement(Text, { style: styles.controlButtonText }, '🏠 תפריט')
)
)
);
}
renderPuzzleGrid() {
const { tiles, gridSize } = this.state;
const rows = [];
for (let i = 0; i < gridSize; i++) {
const rowTiles = [];
for (let j = 0; j < gridSize; j++) {
const index = i * gridSize + j;
rowTiles.push(this.renderTile(tiles[index], index));
}
rows.push(
React.createElement(View, { key: i, style: this.getPuzzleStyles().tileRow }, ...rowTiles)
);
}
return rows;
}
getPuzzleStyles() {
const { width } = Dimensions.get('window');
const boardSize = Math.min(width - 60, 300);
const tileSize = (boardSize - 20) / this.state.gridSize - 4;
return StyleSheet.create({
menuContainer: {
backgroundColor: '#f8f9fa',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
minHeight: 400
},
title: {
fontSize: 28,
fontWeight: 'bold',
color: '#2c3e50',
textAlign: 'center',
marginBottom: 10,
},
subtitle: {
fontSize: 16,
color: '#7f8c8d',
textAlign: 'center',
marginBottom: 30,
},
gameInfo: {
backgroundColor: 'white',
padding: 20,
borderRadius: 15,
marginBottom: 30,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
infoText: {
fontSize: 16,
color: '#2c3e50',
textAlign: 'center',
marginBottom: 8,
},
startButton: {
backgroundColor: '#3498db',
paddingVertical: 15,
paddingHorizontal: 30,
borderRadius: 25,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.2,
shadowRadius: 4,
elevation: 5,
},
buttonText: {
color: 'white',
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
gameContainer: {
backgroundColor: '#f8f9fa',
flex: 1,
padding: 15,
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 20,
backgroundColor: 'white',
padding: 15,
borderRadius: 10,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 2,
},
gameTitle: {
fontSize: 20,
fontWeight: 'bold',
color: '#2c3e50',
},
stats: {
alignItems: 'flex-end',
},
statText: {
fontSize: 14,
color: '#7f8c8d',
marginBottom: 2,
},
puzzleBoard: {
width: boardSize,
height: boardSize,
backgroundColor: 'white',
borderRadius: 15,
padding: 10,
alignSelf: 'center',
marginBottom: 20,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
tileRow: {
flexDirection: 'row',
justifyContent: 'space-around',
marginBottom: 4,
},
tile: {
width: tileSize,
height: tileSize,
backgroundColor: '#3498db',
borderRadius: 8,
justifyContent: 'center',
alignItems: 'center',
margin: 2,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.15,
shadowRadius: 3,
elevation: 3,
},
emptyTile: {
backgroundColor: 'transparent',
shadowOpacity: 0,
elevation: 0,
},
tileText: {
fontSize: tileSize > 60 ? 24 : 18,
fontWeight: 'bold',
color: 'white',
},
completeIndicator: {
backgroundColor: '#2ecc71',
padding: 12,
borderRadius: 10,
alignItems: 'center',
marginBottom: 15,
},
completeText: {
color: 'white',
fontSize: 18,
fontWeight: 'bold',
},
controls: {
flexDirection: 'row',
justifyContent: 'space-around',
marginTop: 10,
},
controlButton: {
backgroundColor: '#3498db',
paddingVertical: 12,
paddingHorizontal: 20,
borderRadius: 20,
minWidth: 120,
alignItems: 'center',
},
menuButton: {
backgroundColor: '#95a5a6',
},
controlButtonText: {
color: 'white',
fontSize: 14,
fontWeight: 'bold',
},
});
}
render() {
console.log('🎨 SimplePuzzleGameComponent rendering...', this.state.currentScreen);
return this.state.currentScreen === 'menu'
? this.renderMenu()
: this.renderGame();
}
}
module.exports = SimplePuzzleGameComponent;
console.log('✅ SimplePuzzleGameComponent loaded successfully');