JSFiddle - React, Tailwind, and code Playground
by jcubed111
HTML
<pre id="output"></pre>
CSS
pre{
font-family: Consolas, monospace;
font-weight: bold;
line-height: 1.18;
}
.roomText{
font-weight: normal;
color: #888;
}
.blocked{
font-weight: bold;
color: #000;
}
.goal{
font-weight: bold;
background-color: #f0a;
}
JavaScript
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
class Room{
constructor(x, y, blocked=false) {
this.x = x;
this.y = y;
this.blocked = blocked;
this.doorNorth = false;
this.doorSouth = false;
this.doorEast = false;
this.doorWest = false;
this.pathIndex = '';
}
roomNorth() { return roomAt(this.x, this.y+1); }
roomSouth() { return roomAt(this.x, this.y-1); }
roomEast() { return roomAt(this.x+1, this.y); }
roomWest() { return roomAt(this.x-1, this.y); }
openNorth(open=true) { this.doorNorth = open; this.roomNorth().doorSouth = open; }
openSouth(open=true) { this.doorSouth = open; this.roomSouth().doorNorth = open; }
openEast(open=true) { this.doorEast = open; this.roomEast().doorWest = open; }
openWest(open=true) { this.doorWest = open; this.roomWest().doorEast = open; }
text() {
if(this.blocked) return ['|||', 'blocked'];
return [this.pathIndex, this.pathIndex==15 ? 'goal' : ''];
}
setBlocked() {
this.blocked = true;
this.openNorth(false);
this.openSouth(false);
this.openEast(false);
this.openWest(false);
}
connectedRooms() {
return ['North', 'South', 'East', 'West'].filter(
dir => this['door' + dir]
).map(
dir => this['room' + dir]()
);
}
}
var rooms = {};
function roomAt(x, y) {
if(x < min || y < min || x > max || y > max) {
return new Room(x, y, true);
}else{
return rooms[x][y];
}
}
var min = -9, max = 9;
for(let x=min; x<=max; x++) {
rooms[x] = {};
for(let y=min; y<=max; y++) {
rooms[x][y] = new Room(x, y);
}
}
function forEachRoom(cb, ctx=null) {
for(let x=min; x<=max; x++) {
for(let y=min; y<=max; y++) {
cb.call(ctx, rooms[x][y], x,...