Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bijeebuss/3fa2f80a536106643d82c04da293eda7 to your computer and use it in GitHub Desktop.
Save bijeebuss/3fa2f80a536106643d82c04da293eda7 to your computer and use it in GitHub Desktop.
function randomInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 0 = left
// 1 = right
// 2 = up
// 3 = down
function randomDirection() {
return randomInt(0, 3);
}
function randomGoodDirection() {
let direction = 0
while(direction == 0) {
direction = randomInt(0, 3);
}
return direction;
}
function addSpace(direction: number) {
if (direction === 0) {
spaces.push([lastSpace()[0] - 1, lastSpace()[1]])
}
else if (direction === 1) {
spaces.push([lastSpace()[0] + 1, lastSpace()[1]])
}
else if (direction === 2) {
spaces.push([lastSpace()[0], lastSpace()[1] + 1])
}
else if (direction === 3) {
spaces.push([lastSpace()[0], lastSpace()[1] - 1])
}
}
function checkWalls(nextDirection: number): boolean {
if(nextDirection == 2 && lastSpace()[1] >= height - 1)
return false;
if(nextDirection == 3 && lastSpace()[1] <= 0)
return false;
return true;
}
function lastSpace(): Array<number> {
return spaces[spaces.length - 1];
}
function printMaze() {
for(let y = 0; y < height - 1; y++) {
let line = '';
for(let x = 0; x < width - 1; x++) {
if(spaces.find(space => {
return space[0] === x && space[1] === y;
})) {
line += ' ';
}
else {
line += '#';
}
}
console.log(line);
}
}
const height = 8;
const width = 23;
const spaces:Array<Array<number>> = [];
const startingPoint = randomInt(1, height-2);
let x = 0;
spaces.push([0, startingPoint]);
while(lastSpace()[0] < width - 1) {
let nextDirection = randomGoodDirection();
while(!checkWalls(nextDirection)) {
nextDirection = randomGoodDirection();
}
addSpace(nextDirection);
}
printMaze();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment