@nichathan-gaming/map-generator
Version:
Creates and generates a 2 dimensional array with various path generation functions.
57 lines (47 loc) • 2.19 kB
JavaScript
import mapGenerator from "../mapGenerator.js";
import assertIndex from "./assertIndex.js";
import { assertInstanceOf, assertType, basicTypes } from "@nichathan-gaming/assertions";
/**
* Counts the neighbors with a certain value around the index.
* If range is less than 1, set the range to the maximum
* Index must be within the bounds of the width and height for multArray
* countDiagonals will count at index +[1, 1], -[1, 1], +[1, -1], -[1, -1] when true
* @param {mapGenerator} map The current game map element
* @param {number} range The maximum size of the path
* @param {[number, number]} searchIndex The index to count neighbors at
* @param {number} countedValue The value to count with
* @param {boolean} countDiagonals Default: false - If it should count diagonal indexes
* @returns {number} The number of indexes around the searchIndex with a value of countedValue
*/
const countNeighbors = (map, range, searchIndex, countedValue, countDiagonals = false) => {
assertInstanceOf(map, mapGenerator);
assertType(range, basicTypes.number);
assertIndex(searchIndex);
map.assertBasicType(countedValue);
assertType(countDiagonals, basicTypes.boolean);
//get multArray dimensions
const height = map.getHeight();
const width = map.getWidth();
if(range < 1) range = width > height ? width : height;
//ensure our indexes are within range
if(!map.isValidIndex(searchIndex)) {
return 5;
};
//initialize count
let count = 0;
//search the neighbors in the multArray and add to count if equality function is true
for(let i = -range; i <= range; i++){//row
for(let j = -range; j <= range; j++){//column
if((i===0 && j===0) || (Math.abs(i)===Math.abs(j) && !countDiagonals)) continue;
const index = [
searchIndex[0] + i,
searchIndex[1] + j
];
if(map.isValidIndex(index) && map.isValueAtIndexEqualToValue(index, countedValue)){
count++;
};
};
};
return count;
};
export default countNeighbors;