Workshop › Frogger-style Crossing › Step 4 of 22
Each arrow press makes the frog hop one square, never off the board. Holding the key does not keep hopping: one press, one hop, like the arcade game.
```js
function hop(dx, dy) {
frog.x = Math.min(COLS - 1, Math.max(0, frog.x + dx))
frog.y = Math.min(START_ROW, Math.max(0, frog.y + dy))
}
const DIRECTIONS = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
document.addEventListener('keydown', (event) => {
const direction = DIRECTIONS[event.key]
if (direction) {
event.preventDefault()
// One hop per press: holding the key down does not hop again.
if (!event.repeat) hop(...direction)
}
})
```Math.max(0, ...) and Math.min(COLS - 1, ...) keep the column between 0 and 11 (and the row between 0 and 12).DIRECTIONS maps each arrow to a [dx, dy] pair; other keys give undefined.hop(...direction) spreads the pair into two arguments.event.repeat is true for the automatic repeats of a held key.Under frog, write hop, DIRECTIONS and the keydown listener.
Skills: Keyboard and mouse input