-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtile-keeper.js
61 lines (52 loc) · 1.32 KB
/
tile-keeper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* The tile keeper tracks which cells need to be retained around the player by
* a view.
* Every turn, the engine declares the cell of interest and the tile keeper
* notes which cells enter or exit the radius around the player.
*/
// @ts-check
import { circle } from './circle.js';
import { setDifference } from './lib/set.js';
/** @typedef {import('./types.js').AdvanceFn} AdvanceFn */
/**
* @callback TileFn
* @param {number} tile
*/
/**
* @callback RenderAroundFn
* @param {number} tile
* @param {number} radius
*/
/**
* @typedef {Object} TileKeeper
* @prop {RenderAroundFn} keepTilesAround
*/
/**
* @param {Object} args
* @param {TileFn} args.enter
* @param {TileFn} args.exit
* @param {AdvanceFn} args.advance
* @returns {TileKeeper}
*/
export function makeTileKeeper({ enter, exit, advance }) {
let nextTiles = new Set();
let prevTiles = new Set();
/**
* @param {number} at
* @param {number} radius
*/
function keepTilesAround(at, radius) {
nextTiles.clear();
for (const t of circle(at, advance, radius)) {
nextTiles.add(t);
}
for (const t of setDifference(nextTiles, prevTiles)) {
enter(t);
}
for (const t of setDifference(prevTiles, nextTiles)) {
exit(t);
}
[nextTiles, prevTiles] = [prevTiles, nextTiles];
}
return { keepTilesAround };
}