Workshop › Blackjack › Step 21 of 22

Buttons

What we are doing

A bar of four buttons at the bottom: Hit, Stand, Double, Deal. A button you can use right now is bright, the others are dim. Clicking or touching one calls the same press as the keys.

```js
const BAR_Y = 404
const BUTTONS = ['Hit', 'Stand', 'Double', 'Deal']
const BUTTON_W = canvas.width / BUTTONS.length

canvas.addEventListener('pointerdown', (event) => {
  const rect = canvas.getBoundingClientRect()
  const x = ((event.clientX - rect.left) * canvas.width) / rect.width
  const y = ((event.clientY - rect.top) * canvas.height) / rect.height
  if (y >= BAR_Y) press(BUTTONS[Math.floor(x / BUTTON_W)])
})

  BUTTONS.forEach((label, i) => {
    const active = label === 'Deal' ? phase === 'done' : phase === 'player' && (label !== 'Double' || player.length === 2)
    ctx.fillStyle = active ? '#f8fafc' : '#4b7a5a'
    ctx.fillRect(i * BUTTON_W + 6, BAR_Y, BUTTON_W - 12, 44)
    ctx.fillStyle = '#14532d'
    ctx.font = 'bold 18px sans-serif'
    ctx.textAlign = 'center'
    ctx.fillText(label, i * BUTTON_W + BUTTON_W / 2, BAR_Y + 29)
  })
```

What it means

Your turn

  1. Under DELAY, write the three button constants.
  2. Above drawCard, write the pointer listener.
  3. At the end of draw, draw the buttons.

Skills: Keyboard and mouse input, Drawing on a canvas

All steps

  1. Cards
  2. A deck
  3. Shuffle
  4. Deal
  5. Cards on the table
  6. Card faces
  7. Keep drawing
  8. What is a hand worth?
  9. Aces: 11 or 1
  10. Hit: one more card
  11. Stand
  12. The hidden card
  13. Chips
  14. Who wins?
  15. The dealer's turn
  16. The next round
  17. Blackjack!
  18. Your record
  19. Double down
  20. Long hands fit
  21. Buttons
  22. Build it yourself: six decks