From 14e7aa3ff79babe0a77ae300a33c768d82d28381 Mon Sep 17 00:00:00 2001 From: Abbey Sparrow Date: Tue, 20 Feb 2024 20:44:17 -0700 Subject: [PATCH] query by tileName --- lib/TileMap.js | 26 +++++++++++++++++++++++++- test/tilemap-query-test.js | 6 ++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/lib/TileMap.js b/lib/TileMap.js index 604ca42..e589580 100644 --- a/lib/TileMap.js +++ b/lib/TileMap.js @@ -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; diff --git a/test/tilemap-query-test.js b/test/tilemap-query-test.js index 7888ec3..e1c1ee9 100644 --- a/test/tilemap-query-test.js +++ b/test/tilemap-query-test.js @@ -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 }); @@ -155,8 +155,10 @@ 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' }); @@ -164,4 +166,4 @@ tap.test('query method returns correct positions for tiles by name', (t) => { t.same(subsection.data, expected, 'Returns correct positions for tiles by name'); t.end(); }); -*/ +//*/