@2d-game-grid/square
Version:
A simple square grid made for games
91 lines (90 loc) • 3.02 kB
JavaScript
import {Cell} from '@2d-game-grid/core'
import {SquareNeighbors} from './SquareNeighbors.js'
import {getDistance} from './algorithms/distance/getDistance.js'
import {getPath} from './algorithms/pathfinding/getPath.js'
import {listCellsInDistance} from './algorithms/distance/listCellsInDistance.js'
import {listReachableCells} from './algorithms/pathfinding/listReachableCells.js'
import {SquareEdges} from './SquareEdges.js'
import {SquareCorners} from './SquareCorners.js'
/**
* A Cell is part of a grid. It contains meta information like its coordinates inside the grid and the corresponding value.
*/
export class SquareCell extends Cell {
grid
/**
* An instance of the cells' neighbors
*/
neighbors
/**
* An instance of the cells' edges
*/
edges
/**
* An instance of the cells' corners
*/
corners
/**
*
* @param grid The grid this cell is part of
* @param coordinate The coordinate in the grid
* @param value The value of the cell
*/
constructor(grid, coordinate, value) {
super(coordinate, value)
this.grid = grid
this.neighbors = new SquareNeighbors(grid, this)
this.edges = new SquareEdges(grid, this)
this.corners = new SquareCorners(grid, this)
}
/**
* @param target The coordinate that the distance should be calculated for
* @param algorithm The used algorithm for the distance calculation
* @returns The distance
*/
getDistance(target, algorithm = 'MANHATTAN') {
return getDistance(this, target, algorithm)
}
/**
* @param maxDistance The maximum distance (including) to a cell that should be returned
* @param algorithm The used algorithm for the distance calculation
* @returns All cells that are in the distance (excluding this cell)
*/
listCellsInDistance(maxDistance, algorithm = 'MANHATTAN') {
return listCellsInDistance(this, maxDistance, algorithm)
}
/**
* @param target The coordinate that the path should end
* @param options The options to customize the pathfinding
* @returns The shortest path including this cell and the target cell
*/
getPath(target, options) {
return getPath(this.grid, this, target, options)
}
/**
* @param maxPathSteps The maximum amount of steps to a cell that should be returned (start and end cell included)
* @param options The options to customize the pathfinding
* @returns All cells that are reachable (excluding the start cell)
*/
listReachableCells(maxPathSteps, options) {
return listReachableCells(this, maxPathSteps, options)
}
/**
* @returns The row of the cell
*/
getRow() {
return this.grid.getRow(this.row)
}
/**
@returns The column of the cell
*/
getColumn() {
return this.grid.getColumn(this.col)
}
/**
* @param cloneValue A custom function to clone the value of this cell (defaults to copying the value)
* @returns The cloned cell
*/
clone(cloneValue = (value) => value) {
return new SquareCell(this.grid, this, cloneValue(this.value))
}
}