Workshop › Conway's Game of Life › Step 14 of 32

A world without edges

What we are doing

At the edges a glider crashes and turns into a block. We make the world wrap around instead: the column after the last one is the first, the row above the top is the bottom. The % (remainder) operator does it.

```js
// Live neighbours among the 8 around (r, c). The edges wrap around, so the world has no border.
function countNeighbors(r, c) {
  let count = 0
  for (let dr = -1; dr <= 1; dr++) {
    for (let dc = -1; dc <= 1; dc++) {
      if (dr === 0 && dc === 0) continue
      count += grid[(r + dr + ROWS) % ROWS][(c + dc + COLS) % COLS]
    }
  }
  return count
}
```

What it means

Your turn

In countNeighbors, replace the lines const nr, const nc and the long if with the single wrapping line, and update the comment above the function.

Skills: Arrays and objects

All steps

  1. The board
  2. Measure the grid
  3. One living cell
  4. A function that draws
  5. The world in memory
  6. Draw every living cell
  7. A random soup
  8. Count the neighbours
  9. Four rules
  10. Draw again and again
  11. Next generation with N
  12. Count the generations
  13. Show the generation
  14. A world without edges
  15. Count the living
  16. A generation every few frames
  17. Let it live
  18. Running or not
  19. One place for the buttons
  20. Space to play, N to step
  21. Clear and shuffle
  22. Where is the pointer?
  23. Which cell?
  24. Click a cell
  25. Paint or erase?
  26. Drag to paint
  27. Patterns from text
  28. The glider gun
  29. Fire the gun
  30. Buttons on the screen
  31. Tap the buttons
  32. Build it yourself: a world at rest