1. How a game loop works
Games redraw the screen about 60 times a second. Each time — one frame — the game loop does three jobs:
- update: move things (the basket, the falling laddoo)
- check: was the laddoo caught? add to the score
- draw: clear and paint everything again
requestAnimationFrame(loop) asks the browser to call loop before the next frame. Calling it again at the end of loop keeps the game running forever.
The browser passes loop the current time in milliseconds. The difference from the last frame, dt (in seconds), makes speed fair on slow and fast phones: y = y + speed * dt.
let x = 0;
function loop() {
x = x + 2; // update
ctx.clearRect(0, 0, 320, 100);
ctx.fillRect(x, 40, 20, 20); // draw
if (x < 300) requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
2. Build the game
The game is ready except for its brain. You will write four small pure functions, then finish the loop.
moveBasket(x, dir, speed, maxX) — like the clamp you wrote earlierupdateLaddoo(laddoo, dt) — the laddoo falls by speed * dtisCaught(laddoo, basket) — the laddoo touches the top of the basketnextScore(score, caught) — one point per catch
The tests try your functions with exact numbers, so the game behaves the same every time. When all checks pass — play it! Can you beat 20?
Challenge: Catch the Laddoos
Finish the game:
moveBasket(x, dir, speed, maxX): return x + dir * speed, kept between 0 and maxXupdateLaddoo(laddoo, dt): return the laddoo with y increased by speed * dtisCaught(laddoo, basket): true when laddoo.y + laddoo.r >= basket.y, laddoo.y - laddoo.r <= basket.y + basket.h, and laddoo.x is between basket.x and basket.x + basket.wnextScore(score, caught): score + 1 when caught, otherwise score- In
draw(), paint the laddoo as an orange circle, and at the end of loop call requestAnimationFrame(loop) so the game keeps running.