Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

query by tileName #8

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion lib/TileMap.js
Original file line number Diff line number Diff line change
@@ -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;
6 changes: 4 additions & 2 deletions test/tilemap-query-test.js
Original file line number Diff line number Diff line change
@@ -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,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();
});
*/
//*/