JSFiddle - React, Tailwind, and code Playground
JavaScript
//which directions can be taken,
//only cardinal in this case, you can be creative with this
var directions = [{ x: -1, y: 0},
{ x: 1, y: 0},
{ x: 0, y: 1},
{ x: 0, y: -1}];
//What can be traversed ?
var PASS_FLOOR = 0x1; // 0001
var PASS_WATER = 0x2; // 0010
// Some terrain types:
// Feel free to embellish with other properties
var terrainTypes = [
{ type: "", canPass: 0},
{ type: "grass", canPass: PASS_FLOOR},
{ type: "water", canPass: PASS_WATER},];
//map should really be a class..
var testMap = [[2, 2, 2, 2, 2],
[1, 1, 1, 2, 2],
[1, 1, 2, 2, 2],
[1, 2, 2, 1, 1]];
/* Get a tile at a location, ideally this should be a function of the map object..
dont trust map at all, trust that location has .x and .y */
function getTile(map, location) {
if (map && map[location.x] && map[location.x][location.y])
return terrainTypes[map[location.x][location.y]];
return false;
}
/* This could be cleaner.. */
function getNeighbours(map, location, directions_optional) {
var i;
var neighbours = [];
//make sure we start with something
location.trace = location.trace || [];
//This code still has far too many globals, that should all get fixed
var vectors = directions_optional || directions;
for (i = 0; i < vectors.length; i++) {
var newX = location.x + vectors[i].x;
var newY = location.y + vectors[i].y;
if (!map[newX]) map[newX] = [];
if (!map[newX][newY])
{
map[newX][newY] = {
x: newX,
y: newY,
//distance from origin
d: (location.d || 0) + 1,
//how did we get here
trace: location.trace.slice(0)
}
}
else
{
continue;
}
map[newX][newY].trace.push({ x: newX, y: newY });
neighbours.push(map[newX][newY]);
}
...