Robot Eats Candies on a Grid
A grid is already rendered, with walls, candies and a robot, and helpers for the cells are provided. Make the robot move and eat the candies it reaches. Build it in plain JavaScript or in React, switchable above the editor; in React the board data and inBounds are in game.js.
Requirements
- Arrow keys move the robot one cell; walls and the grid edge block the move. A candy on the destination is eaten and the status line counts it.
- The Eat the nearest candy button finds the shortest path to the closest reachable candy and walks it one cell every
STEP_MSmilliseconds, eating on arrival. When no candy is reachable it does nothing. - Drive the walk with
requestAnimationFrame, notsetIntervalorsetTimeout. Decide when to step from the frame timestamps, so the pace does not depend on the display's frame rate. - A second click during a walk does nothing. An arrow key cancels the walk with
cancelAnimationFrame, then moves the robot from where it stands. - Whenever the robot has stood still for
HINT_MSmilliseconds (after the page loads, after the last arrow key, or after a walk ends), highlight the shortest path to the nearest candy. An arrow key hides the hint at once and restarts the wait, and the button cancels a pending hint. Write thedebounce(fn, ms)behind it yourself, with acancel(). - In plain JavaScript, re-rendering only toggles classes on the existing cells; the grid is not rebuilt. In React, keep the cell classes (
cell--wall,cell--candy,cell--robot,cell--hint) on cells in row-major order: the styles and the tests read them.
Clarify first, as the reports differ: does the player drive the robot or does it move by itself? Here it is both.
Hints
Hint 1
step is a direction lookup plus the inBounds check; Set.delete returns whether a candy was there, so it doubles as the eat check. In React, a reducer returns a new game with a copied Set instead.
Hint 2
Breadth-first search from the robot with a predecessor map; the first candy dequeued is the nearest, and walking the map back from it gives the path. Use an index pointer over the queue array instead of shift().
Hint 3
Keep one walk object: the path, the next index, the timestamp of the last step and the pending frame ID. Each frame steps only when now - last >= STEP_MS. Keep the frame ID for cancelAnimationFrame; a non-null walk is also what makes a second click a no-op.
Hint 4
debounce keeps one timer: each call clears it and starts a new one, and cancel clears it. The hint is then two calls on every key press: hide it now, and call the debounced show.
Hint 5
In React, create the debounced function once per component, with useState or a ref, and have it call the latest callback through a ref. Otherwise the pending call computes the path from the state of an old render.
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.