Skip to content

Commit 14e7aa3

Browse files
committed
query by tileName
1 parent ddd627f commit 14e7aa3

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

lib/TileMap.js

+25-1
Original file line numberDiff line numberDiff line change
@@ -179,8 +179,32 @@ export default class TileMap {
179179

180180
query({ x, y, width, height, z, tileName } = {}) {
181181
let results = [];
182+
if(tileName !== undefined){
183+
const id = this.getTileIdByName(tileName);
184+
if(!Number.isInteger(id)) throw new Error(`tile name '${tileName}' not found`)
185+
const xRangeOpen = x || 0;
186+
const yRangeOpen = y || 0;
187+
const xRangeClose = width || this.width;
188+
const yRangeClose = height || this.height;
189+
let index = null;
190+
for (let offsetY = yRangeOpen; offsetY < yRangeClose; offsetY++) {
191+
for (let offsetX = xRangeOpen; offsetX < xRangeClose; offsetX++) {
192+
if (offsetX >= this.width || offsetY >= this.height) {
193+
continue;
194+
} else {
195+
index = offsetY * this.width + offsetX; // Calculate the correct index in the 1D array
196+
if (this.data[index] === id) {
197+
results.push({
198+
x: offsetX,
199+
y: offsetY
200+
});
201+
}
202+
}
203+
}
204+
}
205+
}
182206

183-
if (x !== undefined && y !== undefined && width !== undefined && height !== undefined) {
207+
if (x !== undefined && y !== undefined && width !== undefined && height !== undefined && !tileName) {
184208
for (let offsetY = 0; offsetY < height; offsetY++) {
185209
for (let offsetX = 0; offsetX < width; offsetX++) {
186210
const queryX = x + offsetX;

test/tilemap-query-test.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ tap.test('query method can return the entire map', (t) => {
143143
t.end();
144144
});
145145

146-
/*
146+
//*
147147
// Test querying by tile name
148148
tap.test('query method returns correct positions for tiles by name', (t) => {
149149
const tileMap = new TileMap({ width: 3, height: 3 });
@@ -155,13 +155,15 @@ tap.test('query method returns correct positions for tiles by name', (t) => {
155155
tileMap.data[4] = 1; // Tile with name corresponding to ID 1 at (1, 1)
156156
tileMap.data[7] = 1; // Tile with name corresponding to ID 1 at (1, 2)
157157

158+
console.log(tileMap.getTileIdByName)
158159
// Mock the getTileIdByName function to return 1 for a specific tile name
159160
tileMap.getTileIdByName = (tileName) => tileName === 'TestTile' ? 1 : undefined;
161+
console.log(tileMap.getTileIdByName)
160162

161163
const subsection = tileMap.query({ tileName: 'TestTile' });
162164

163165
const expected = [{ x: 1, y: 0 }, { x: 1, y: 1 }, { x: 1, y: 2 }];
164166
t.same(subsection.data, expected, 'Returns correct positions for tiles by name');
165167
t.end();
166168
});
167-
*/
169+
//*/

0 commit comments

Comments
 (0)