Workshop › Tic-tac-toe › Step 4 of 33
Repeat with a loop
What we are doing
The second vertical line sits at x = 200, which is 2 * CELL. Instead of copying the line, we let a for loop
draw it for i = 1 and i = 2.
```js
for (let i = 1; i < 3; i++) {
ctx.fillRect(i * CELL - 2, 0, 4, canvas.height)
}
```
What it means
let i = 1 starts a counter at 1; i < 3 keeps going while it is below 3; i++ adds 1 after each round.
- So the body runs twice:
i = 1 draws at 98, i = 2 draws at 198.
* is multiplication.
Your turn
Replace the line ctx.fillRect(CELL - 2, 0, 4, canvas.height) with the loop (the fillRect inside it uses
i * CELL). Press Run.
Skills: Loops
← The first grid line Finish the grid →
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