Workshop › Tic-tac-toe › Step 24 of 33

Click to play again

What we are doing

When the round is over, the next click starts a new one instead of playing. We also tell the player so, under the result.

```js
canvas.addEventListener('click', (event) => {
  if (result) {
    reset()
  } else {
    // The canvas may be displayed at a different size than its 300×300 pixels, so scale the click.
    const rect = canvas.getBoundingClientRect()
    const x = (event.clientX - rect.left) * (canvas.width / rect.width)
    const y = (event.clientY - rect.top) * (canvas.height / rect.height)
    const index = Math.floor(y / CELL) * 3 + Math.floor(x / CELL)
    play(index)
  }
  draw()
})

    ctx.font = '14px sans-serif'
    ctx.fillText('Click to play again', canvas.width / 2, 172)
```

What it means

Your turn

  1. In the click listener, wrap the old lines (from the comment to play(index)) in if (result) { reset() } else { ... }.
  2. In draw, under the result fillText, add the two Click to play again lines.

Skills: Keyboard and mouse input, Game states

All steps

  1. Get the canvas and the pen
  2. Paint the board
  3. The first grid line
  4. Repeat with a loop
  5. Finish the grid
  6. The board as a list
  7. A function that draws
  8. Write an X
  9. From cell number to position
  10. Draw what the board holds
  11. A color for each mark
  12. Make a move
  13. No playing on a taken cell
  14. Listen for clicks
  15. Which cell was clicked?
  16. Clicks on any screen size
  17. The eight winning lines
  18. Find three in a row
  19. Win, draw or go on
  20. The round ends
  21. Show who won
  22. Light up the winning line
  23. A function for a fresh round
  24. Click to play again
  25. A computer that picks a cell
  26. The computer answers
  27. Rule one: take the center
  28. Rule two: win when you can
  29. Rule three: block the opponent
  30. Score a finished game
  31. Look ahead: minimax
  32. A computer that never loses
  33. Build it yourself: keep score