Skip to content

Instantly share code, notes, and snippets.

@dotspencer
Created September 26, 2019 18:18
Show Gist options
  • Save dotspencer/151032486c48f4230a6eddd2524b03d3 to your computer and use it in GitHub Desktop.
Save dotspencer/151032486c48f4230a6eddd2524b03d3 to your computer and use it in GitHub Desktop.
Simple Maze Graph Generator
(() => {
const dim = 7;
const graph = {};
const path = [];
// create graph
for (let i = 0; i < dim*dim; i++) {
const row = i % dim;
const col = Math.floor(i / dim);
const edges = [
getIndex(row + 1, col),
getIndex(row -1, col),
getIndex(row, col + 1),
getIndex(row, col - 1),
].filter(e => e != null);
graph[i] = {
edges: shuffle(edges),
};
}
// create maze path
explore(graph, 0);
console.log('graph:', graph);
console.log('path:', path);
function getIndex(row, col) {
if (row >= dim || row < 0 || col >= dim || col < 0) return null;
return (col * dim) + row;
}
function shuffle(array) {
for(let i = 0; i < array.length; i++){
const randomIndex = Math.floor(Math.random() * array.length);
const temp = array[i];
array[i] = array[randomIndex];
array[randomIndex] = temp;
}
return array;
}
function explore(graph, currentIndex) {
const current = graph[currentIndex];
current.visited = true;
for (let i = 0; i < current.edges.length; i++) {
const nextIndex = current.edges[i];
const next = graph[nextIndex];
if (!next.visited) {
path.push([currentIndex, nextIndex]);
explore(graph, nextIndex);
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment