Workshop › Puzzle Bobble-style Bubble Shooter › Step 4 of 31

Draw the grid

What we are doing

cellPos(r, c) turns a cell into a position on the canvas; all the geometry lives in this one function. Then draw visits every cell and draws the ones that are not empty. A strip at the top leaves room for the score.

```js
const TOP = 30 // room for the score

const cellPos = (r, c) => ({ x: R + c * 2 * R, y: TOP + R + r * 2 * R })

  ctx.fillStyle = '#312e81'
  ctx.fillRect(0, 0, canvas.width, TOP)

  for (let r = 0; r < ROWS; r++) {
    for (let c = 0; c < COLS; c++) {
      if (grid[r][c] < 0) continue
      const p = cellPos(r, c)
      drawBubble(p.x, p.y, grid[r][c])
    }
  }
```

What it means

Your turn

  1. Under ROWS write TOP.
  2. Under let grid ..., leave an empty line and write cellPos.
  3. In draw, replace the test bubble with the strip and the two loops. Press Run.

Skills: Drawing on a canvas, Loops

All steps

  1. The night sky
  2. One bubble
  3. A grid of cells
  4. Draw the grid
  5. Bubbles that nest
  6. The shooter
  7. Aim upwards
  8. Turn with the arrows
  9. Aim with the pointer
  10. Fire!
  11. Fly
  12. Bounce off the walls
  13. Touching something?
  14. Stick into the grid
  15. Smaller steps
  16. Six neighbours
  17. Flood fill
  18. Three in a row pop
  19. Bubbles that fall
  20. Cut them loose
  21. Show the score
  22. Only useful colors
  23. Count the shots
  24. The ceiling comes down
  25. Win or lose
  26. The danger line
  27. The end message
  28. Play again
  29. Best score
  30. A dotted guide
  31. Build it yourself: swap bubbles