import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
const CricketGame = () => {
const players = ['Player 1', 'Player 2', 'Player 3'];
const targetScore = 30;
const [scores, setScores] = useState({});
const [turns, setTurns] = useState({});
const [gameOver, setGameOver] = useState(false);
const [currentTurn, setCurrentTurn] = useState(0);
const playTurn = (playerIndex) => {
if (gameOver || playerIndex !== currentTurn) return;
const score = Math.floor(Math.random() * 6) + 1;
const currentPlayer = players[playerIndex];
const updatedScores = {
...scores,
[currentPlayer]: (scores[currentPlayer] || 0) + score,
};
const updatedTurns = {
...turns,
[currentPlayer]: (turns[currentPlayer] || 0) + 1,
};
setScores(updatedScores);
setTurns(updatedTurns);
if (updatedScores[currentPlayer] >= targetScore) {
// Game over, show match summary
showMatchSummary(updatedScores, updatedTurns);
} else {
// Move to the next player's turn
setCurrentTurn((currentTurn + 1) % players.length);
}
};
const showMatchSummary = (updatedScores, updatedTurns) => {
setScores(updatedScores);
setTurns(updatedTurns);
setGameOver(true);
};
const getOrdinalSuffix = (number) => {
const suffixes = ['st', 'nd', 'rd'];
const v = number % 100;
return number + (suffixes[(v - 20) % 10] || suffixes[v] || 'th');
};
return (
<View style={styles.container}>
{players.map((player, index) => (
<TouchableOpacity
key={player}
style={[styles.button, { backgroundColor: index === currentTurn ? 'lightblue' : 'gray' }]}
onPress={() => playTurn(index)}
disabled={gameOver || scores[player] >= targetScore || currentTurn !== index}
>
<Text>{`${player}'s Turn\nScore: ${scores[player] || 0}\n${turns[player] || 0} Turns`}</Text>
</TouchableOpacity>
))}
<Text style={styles.targetScore}>{`Target Score: ${targetScore}`}</Text>
{/* Display match summary if the game is over */}
{gameOver && (
<Text>{`Match Summary\n${Object.keys(scores)
.sort((a, b) => scores[b] - scores[a])
.map((player, index) => `${getOrdinalSuffix(index + 1)}: ${player}, Score: ${scores[player]}, No of Turns: ${turns[player]}`)
.join('\n')}`}</Text>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
padding: 10,
margin: 10,
},
targetScore: {
marginTop: 20,
},
});
export default CricketGame;