Workshop › Pinball › Step 27 of 42

Which keys are held?

What we are doing

A flipper stays up while its key is held. So we need to know not only when a key goes down but also when it comes back up. pressed remembers the two flipper keys; one function key handles both events.

```js
let pressed // { left, right }

  pressed = { left: false, right: false }

function key(event, down) {
  const k = event.key
  if (k === 'ArrowLeft' || k === 'z' || k === 'Z') pressed.left = down
  else if (k === 'ArrowRight' || k === '/' || k === 'm' || k === 'M') pressed.right = down
  else if (k === ' ' || k === 'ArrowDown') {
    if (down) launch()
  } else return
  event.preventDefault()
}

document.addEventListener('keydown', (event) => key(event, true))
document.addEventListener('keyup', (event) => key(event, false))
```

What it means

Your turn

  1. Under let flippers write let pressed.
  2. In reset, under the flippers = ... line, write the pressed line.
  3. Replace the whole keydown listener with key and the two new listeners.

Skills: Keyboard and mouse input

All steps

  1. Paint the table
  2. Draw one wall
  3. A list of walls
  4. The game loop
  5. A ball in the lane
  6. Draw the ball
  7. Move by the velocity
  8. Launch with Space
  9. Gravity
  10. Does the ball touch a wall?
  11. Push the ball out
  12. Bounce off the wall
  13. Small steps and a speed limit
  14. Ready or playing
  15. The next ball
  16. Three bumpers
  17. The ball meets a bumper
  18. A bumper kicks
  19. A score and a fresh start
  20. Points for every hit
  21. Remember which bumper was hit
  22. Light it up
  23. Lit for a moment, points once
  24. Two flippers
  25. Where is the tip?
  26. Flippers stop the ball
  27. Which keys are held?
  28. Which way to turn
  29. Flip!
  30. A moving wall
  31. The flipper throws
  32. Three balls
  33. Balls left and game over
  34. Play again
  35. Remember the best score
  36. Launch on letting go
  37. Pull the spring
  38. Show the spring
  39. Two thumbs
  40. Pull with a finger
  41. Tap to play again
  42. Build it yourself: slingshots