@nichathan-gaming/map-generator
Version:
Creates and generates a 2 dimensional array with various path generation functions.
45 lines (36 loc) • 1.73 kB
JavaScript
import countNeighbors from "../helpers/countNeighbors.js";
import getNewIndexes from "./getNewIndexes.js";
import mapGenerator from "../mapGenerator.js";
import assertIndex from "../helpers/assertIndex.js";
import {assertInstanceOf, assertType, basicTypes} from '@nichathan-gaming/assertions';
/**
* Generates a path through the map
* using Prim's algorithm : Wikipedia Link : https://en.wikipedia.org/wiki/Prim%27s_algorithm
* @param {mapGenerator} map The current game map element
* @param {number} maxPathSize The maximum size for the path
* @param {[number, number]} startIndex The index that the path begins at
*/
const primsGenerator = (map, maxPathSize, startIndex) => {
assertInstanceOf(map, mapGenerator);
assertType(maxPathSize, basicTypes.number);
assertIndex(startIndex);
//get the walkable value
const baseValue = map.getWalkableValue();
//set the startIndex
map.setWalkableValueAtIndex(startIndex);
//initialize the map locations to path along
const mapLocations = getNewIndexes(map, [0, 0], [], baseValue);
while(mapLocations.length){
//get the next index
const nextIndex = mapLocations.splice(0, 1)[0];
//check the number of neighbors
const neighborCount = countNeighbors(map, 1, nextIndex, baseValue, false);
if(neighborCount <= maxPathSize){
//the index is valid, set it as a path
map.setWalkableValueAtIndex(nextIndex);
//add new locations to the beginning of mapLocations based on this index
mapLocations.unshift(...getNewIndexes(map, nextIndex, mapLocations, baseValue));
};
};
};
export default primsGenerator;