Skip to content

Instantly share code, notes, and snippets.

@katrotz
Created March 5, 2019 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katrotz/6a66c98c757e4ea95cac142e3c3e4e29 to your computer and use it in GitHub Desktop.
Save katrotz/6a66c98c757e4ea95cac142e3c3e4e29 to your computer and use it in GitHub Desktop.
Dungeon generator
const HEIGHT = 40;
const WIDTH = 80;
const map = [];
const PLAYER = '@';
const TREASURE = '$';
const ROCK = ' ';
const CORNER = '!';
const WALL = '#';
const FLOOR = '.';
const DOOR1 = '+';
const DOOR2 = '\'';
function rand (val) {
return Math.floor(Math.random() * val);
}
function cave (start) {
const width = rand(10) + 5;
const height = rand(6) + 3;
const left = rand(WIDTH - width - 2) + 1;
const top = rand(HEIGHT - height - 2) + 1;
for (let y = top - 1; y < top + height + 2; y++) {
for (let x = left - 1; x < left + width + 2; x++) {
if (map[y][x] === FLOOR)
return;
}
}
let doors = 0;
let door_x;
let door_y;
if (!start) {
for (let y = top - 1; y < top + height + 2; y++) {
for (let x = left - 1; x < left + width + 2; x++) {
let s = x < left || x > left + width;
let t = y < top || y > top + height;
if (s ^ t && map[y][x] === WALL) {
doors++;
if (rand(doors) === 0) {
door_x = x;
door_y = y;
}
}
}
}
if (doors === 0) {
return;
}
}
for (let y = top - 1; y < top + height + 2; y++) {
for (let x = left - 1; x < left + width + 2; x++) {
let s = x < left || x > left + width;
let t = y < top || y > top + height;
map[y][x] = s && t ? CORNER : (s ^ t ? WALL : FLOOR);
}
}
if (doors > 0) {
map[door_y][door_x] = rand(2) ? DOOR2 : DOOR1;
}
for (let j = 0; j < (start ? 1 : rand(6) + 1); j++) {
map[rand(height) + top][rand(width) + left] =
start ? PLAYER :
(rand(4) === 0 ? TREASURE : String.fromCharCode(rand(62) + 65));
}
}
function generate () {
for (let y = 0; y < HEIGHT; y++) {
map[y] = [];
for (let x = 0; x < WIDTH; x++) {
map[y][x] = ROCK;
}
}
for (let j = 0; j < 1000; j++) {
cave(j === 0);
}
}
generate();
console.log(map.map(r => r.map(c => c === CORNER ? WALL : c).join('')).join('\n'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment