Workshop › Tower Defense › Step 5 of 42
findRoad walks from each corner to the next, one tile at a time, and puts every tile it passes into a Set of keys
like '3,4'. Math.sign gives exactly the step to take, so one loop works for all four directions.
```js
let road // keys of the tiles the road covers
const key = (col, row) => col + ',' + row
// Every tile between two corners, corner included.
function findRoad() {
road = new Set()
for (let i = 1; i < PATH.length; i++) {
let [x, y] = PATH[i - 1]
const [tx, ty] = PATH[i]
while (true) {
road.add(key(x, y))
if (x === tx && y === ty) break
x += Math.sign(tx - x)
y += Math.sign(ty - y)
}
}
}
function reset() {
findRoad()
}
reset()
requestAnimationFrame(loop)
```Set holds each value at most once; add puts one in, has asks if it is there.key(3, 4) is the string '3,4': strings can be found again in a Set, arrays cannot.let [x, y] starts at the first; while (true) repeats until break, when the second is
reached. Math.sign(tx - x) is 1, -1 or 0: one step towards the target, or none.PATH, after an empty line, write let road, key, findRoad and reset.reset() above requestAnimationFrame(loop).Skills: Arrays and objects, Loops
← The road as corners Draw the road →