| Level Navigation: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18⚡ | 19 |
User Story: As a player, I want the apple to change size randomly so that the game becomes more challenging and interesting.
Create a utility function for random numbers and make the apple size change on each click.
randomNumber(a, b) helper function outside the App component
a and bMath.random() and Math.floor()appleSize with initial value of 100randomSize() function that sets appleSize to a random value between 20 and 100randomSize() in both clickTarget and missTarget functionsappleStyle object with dynamic width and heightstyle attributeNeed help with random numbers and dynamic styling? Check out these snippets:
function randomNumber(a, b) {
return Math.floor(Math.random() * (b - a) + a);
}
function App() {
// ... state and functions
}
const [score, setScore] = useState(0)
const [lives, setLives] = useState(3)
const [appleSize, setAppleSize] = useState(100) // NEW
function randomSize() {
const randomSize = randomNumber(20, 100)
setAppleSize(randomSize)
}
function clickTarget(event) {
event.stopPropagation();
setScore(score + 1)
randomSize(); // NEW
}
function missTarget() {
setLives(lives - 1)
randomSize(); // NEW
}
const appleStyle = {
width: appleSize + "px",
height: appleSize + "px"
}
return (
<>
{/* ... stats div ... */}
<div className='orchard-background' onClick={missTarget}>
<div className="apple-target" onClick={clickTarget} style={appleStyle}></div>
</div>
</>
)
randomSize() is called in both handlersstyle={appleStyle}How Math.random() works:
Math.random() returns a decimal between 0 and 1(b - a) to scale ita to shift to desired rangeMath.floor() rounds down to get an integer