Skip to content

Commit

Permalink
query by tileName
Browse files Browse the repository at this point in the history
  • Loading branch information
khrome committed Feb 21, 2024
1 parent ddd627f commit 14e7aa3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
26 changes: 25 additions & 1 deletion lib/TileMap.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,32 @@ export default class TileMap {

query({ x, y, width, height, z, tileName } = {}) {
let results = [];
if(tileName !== undefined){
const id = this.getTileIdByName(tileName);
if(!Number.isInteger(id)) throw new Error(`tile name '${tileName}' not found`)
const xRangeOpen = x || 0;
const yRangeOpen = y || 0;
const xRangeClose = width || this.width;
const yRangeClose = height || this.height;
let index = null;
for (let offsetY = yRangeOpen; offsetY < yRangeClose; offsetY++) {
for (let offsetX = xRangeOpen; offsetX < xRangeClose; offsetX++) {
if (offsetX >= this.width || offsetY >= this.height) {
continue;
} else {
index = offsetY * this.width + offsetX; // Calculate the correct index in the 1D array
if (this.data[index] === id) {
results.push({
x: offsetX,
y: offsetY
});
}
}
}
}
}

if (x !== undefined && y !== undefined && width !== undefined && height !== undefined) {
if (x !== undefined && y !== undefined && width !== undefined && height !== undefined && !tileName) {
for (let offsetY = 0; offsetY < height; offsetY++) {
for (let offsetX = 0; offsetX < width; offsetX++) {
const queryX = x + offsetX;
Expand Down
6 changes: 4 additions & 2 deletions test/tilemap-query-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ tap.test('query method can return the entire map', (t) => {
t.end();
});

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

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

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

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

0 comments on commit 14e7aa3

Please sign in to comment.