codex-lv3-may-2025

Level Navigation: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18⚡ 19

Level 6: Add Lives Tracking

User Story: As a player, I want to lose a life when I miss the apple so that the game has challenge and consequences.

What You’ll Do

Add a lives state variable and create a miss handler for clicking the background.

Instructions

💡 Code Hints

Need help with multiple state variables? Check out these snippets:

Show Me: adding lives state
function App() {
  const [score, setScore] = useState(0)
  const [lives, setLives] = useState(3)  // NEW
  
  // ... rest of component
}
Show Me: miss handler function
function missTarget() {
  setLives(lives - 1)
}
Show Me: updated JSX with onClick handlers
return (
  <>
    <div className="stats">
      Score: {score} Lives: {lives}
    </div>
    <div className='orchard-background' onClick={missTarget}>
      <div className="apple-target" onClick={clickTarget}></div>
    </div>
  </>
)

✅ Check

  1. You should see “Score: 0 Lives: 3” in the stats bar
  2. Click the apple - score increases, lives stay the same
  3. Click the background (miss the apple) - lives decrease
  4. Click the apple again - only score increases (lives unchanged)
  5. If both handlers fire when clicking apple:
    • Make sure event.stopPropagation() is in clickTarget

Understanding Event Propagation: Try removing event.stopPropagation() temporarily to see what happens. You’ll notice clicking the apple triggers BOTH handlers because clicks “bubble up” from child to parent. That’s why we need stopPropagation()!