Created
March 5, 2019 21:35
-
-
Save katrotz/6a66c98c757e4ea95cac142e3c3e4e29 to your computer and use it in GitHub Desktop.
Dungeon generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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