> loading_
// File: app/page.tsx
// We've enhanced the game's core logic to make the opponent smarter.
// Here's a look at how the dynamic difficulty adjustment works.
// 1. First, we introduce new state to track game history.
// This allows the AI to learn from past outcomes.
const [winLossHistory, setWinLossHistory] = useState<('win' | 'loss')[]>([]);
const [opponentStrength, setOpponentStrength] = useState(0.5); // Base strength
// 2. We created a new function to calculate the opponent's strength.
// This function analyzes the player's recent performance to adjust the difficulty.
const calculateOpponentStrength = (history: ('win' | 'loss')[]) => {
// Base strength is 50%.
let newStrength = 0.5;
const recentGames = history.slice(-5); // Look at the last 5 games.
// If the player has won most recent games, increase difficulty.
const recentWins = recentGames.filter(result => result === 'win').length;
if (recentWins > 3) {
newStrength += 0.15; // Make opponent stronger
}
// If the player has lost most recent games, decrease difficulty.
const recentLosses = recentGames.filter(result => result === 'loss').length;
if (recentLosses > 3) {
newStrength -= 0.15; // Make opponent weaker
}
// Ensure strength stays within reasonable bounds (e.g., 0.2 to 0.8).
return Math.max(0.2, Math.min(0.8, newStrength));
};
// 3. Finally, in our game logic `useEffect`, we replace the static
// Math.random() with our new adaptive AI calculation.
useEffect(() => {
// --- BEFORE THE CHANGE ---
// The opponent's pull was a simple random value.
// const opponentPull = Math.random() * 0.02;
// --- AFTER THE CHANGE ---
// Now, the opponent's strength is calculated before each round.
const newStrength = calculateOpponentStrength(winLossHistory);
setOpponentStrength(newStrength);
// The opponent's pull in the game loop is now based on this adjusted strength.
const opponentPull = opponentStrength * 0.02;
// ... rest of the game logic ...
// When a game ends, we update the history.
// e.g., on player win: setWinLossHistory(prev => [...prev, 'win']);
}, [gameState, winLossHistory]); // Recalculate when game state or history changes.