)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Array Based Collision Cells

  1. ((
  2.   d = document,
  3.   b = d.body,
  4.   canvas = b.appendChild(
  5.     d.createElement('canvas')
  6.   ),
  7.   c = canvas.getContext('2d'),
  8.   r = _ => Math.random(),
  9.   map = [
  10.     [0, 0, 0, 0, 0, 2],
  11.     [1, 1, 0, 0, 0, 1],
  12.     [1, 1, 2, 0, 0, 0],
  13.     [2, 2, 0, 0, 0, 1],
  14.     [0, 1, 0, 0, 2, 0],
  15.     [2, 0, 0, 0, 2, 1],
  16.   ],
  17.   mapW = map[0].length,
  18.   mapH = map.length,
  19.   cols = [, 'red', 'black'],
  20.   cell = (
  21.     x, y, idx,
  22.     col = cols[idx],
  23.     size = 30,
  24.     xp = x * size,
  25.     yp = y * size,
  26.     dir, 
  27.     mv = f => {
  28.       map[y][x] = 0
  29.       f()
  30.       map[y][x] = idx
  31.     }
  32.   ) => (move) => {
  33.     if (move) {
  34.       dir = ~~(r() * 4)
  35.       if (dir == 0 &&
  36.         x != 0 &&
  37.         map[y][x - 1] == 0) {
  38.         mv(_ => x--)
  39.       } else if (dir == 1 &&
  40.         x != mapW - 1 &&
  41.         map[y][x + 1] == 0) {
  42.         mv(_ => x++)
  43.       } else if (dir == 2 &&
  44.         y != 0 &&
  45.         map[y - 1][x] == 0) {
  46.         mv(_ => y--)
  47.       } else if (dir == 3 &&
  48.         y != mapH - 1 &&
  49.         map[y + 1][x] == 0
  50.       ) {
  51.         mv(_ => y++)
  52.       }
  53.     }
  54.  
  55.     xp += (x * size - xp) / 4
  56.     yp += (y * size - yp) / 4
  57.     c.fillStyle = col
  58.     c.fillRect(xp, yp, size, size)
  59.     c.strokeStyle = 'gray'
  60.     c.strokeRect(xp, yp, size, size)
  61.   },
  62.   cells = [],
  63.   w, h, idx, val, i, j,
  64.   draw = () => {
  65.     c.fillStyle = 'gray'
  66.     c.fillRect(0, 0, w, h)
  67.  
  68.     idx = ~~(r() * mapH * mapW)
  69.  
  70.     cells.forEach((cell, i) =>
  71.       cell(idx == i && r() < .3))
  72.   }
  73. ) => {
  74.   b.style.margin = 0
  75.  
  76.   onresize = () => {
  77.     w = canvas.width = innerWidth
  78.     h = canvas.height = innerHeight
  79.     draw()
  80.   }
  81.   onresize()
  82.  
  83.   for (i = 0; i < mapH; i++) {
  84.     for (j = 0; j < mapW; j++) {
  85.       val = map[i][j]
  86.       if (val != 0) cells.push(cell(j, i, val)) 
  87.     }
  88.   }
  89.  
  90.   setInterval(draw, 16)
  91. })()

Array based avoid. I was about to port an old thing that was similar to this and then thought it would be more fun to speedcode it instead. The result is a slightly golfed version of this old thing.

snippet.zone ~ 2021-24 /// {s/z}