Workshop › Tic-tac-toe › Step 7 of 33
A function that draws
What we are doing
Every time a mark is placed, the whole board must be drawn again. We put the drawing lines in a function named
draw, so one word repaints everything.
```js
function draw() {
ctx.fillStyle = '#1e1e2e'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = '#585b70'
for (let i = 1; i < 3; i++) {
ctx.fillRect(i * CELL - 2, 0, 4, canvas.height)
ctx.fillRect(0, i * CELL - 2, canvas.width, 4)
}
}
draw()
```
What it means
function draw() { ... } defines the recipe; it does not run yet.
- The body is indented by two spaces.
draw() with parentheses runs it. It paints the background first, which wipes the old picture.
Your turn
Wrap all the drawing lines in function draw() { ... } (indent them by two spaces) and call draw() after it.
Skills: Functions
← The board as a list Write an X →
All steps
- Get the canvas and the pen
- Paint the board
- The first grid line
- Repeat with a loop
- Finish the grid
- The board as a list
- A function that draws
- Write an X
- From cell number to position
- Draw what the board holds
- A color for each mark
- Make a move
- No playing on a taken cell
- Listen for clicks
- Which cell was clicked?
- Clicks on any screen size
- The eight winning lines
- Find three in a row
- Win, draw or go on
- The round ends
- Show who won
- Light up the winning line
- A function for a fresh round
- Click to play again
- A computer that picks a cell
- The computer answers
- Rule one: take the center
- Rule two: win when you can
- Rule three: block the opponent
- Score a finished game
- Look ahead: minimax
- A computer that never loses
- Build it yourself: keep score