JSFiddle - React, Tailwind, and code Playground

by David Marshall

HTML

<body>
    <canvas id="canvas"></canvas>
</body>

CSS

html, body {
    margin: 0px;
}
canvas {
    display: block;
    width: 864px;
    height: 864px;
    border: 1px solid black;
}

JavaScript

//when the window loads and is ready to draw things
window.onload = function () {
    
    //Set up the canvas object for drawing
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    //Get relevant variables to drawing
    canvas.width = 864;
    canvas.height = 864;
    var gridSize = 16;
    var gridWidth = (canvas.width / gridSize);
    var gridHeight = (canvas.height / gridSize);
    
    //How many rooms the program should try to spawn
    var roomCount = 30;
    
    //Create an array of all possible room sizes
    var roomSizes = [];
    for (var n=2; n<7; n++) {
        for (var m=2; m<7; m++) {
            var thisSize = new Array(2);
            thisSize[0] = n;
            thisSize[1] = m;
            roomSizes.push(thisSize);
        }
    }
    
    //Create an array of all the rooms that will be placed
    var rooms = [];
    //Loop through the number of rooms to be placed
    for (var i = 0; i < roomCount; i++) {
        //Select a random position that is weighted toward the center of the grid
        var randX = utils.randomInt(20, gridWidth - 20);
        var randY = utils.randomInt(20, gridHeight - 20);
        //Grab a random room size
        var thisRSI = utils.randomInt(0, roomSizes.length - 1);
        //Create a new room object for the current room, adding it to the rooms array
        rooms.push(room.create(randX - 1, randY - 1, roomSizes[thisRSI][0] + randX + 1, roomSizes[thisRSI][1] + randY + 1, roomSizes[thisRSI][0], roomSizes[thisRSI][1]));
    }

    //As long as this variable is true, the program will continue to seperate the rooms
    var continueLoop = false;
    //Set the maximum number of seperation code iterations
    var loopTimeout = 50;
    //While the rooms are not seperated
    do {
        continueLoop = false;
        //Loop through all rooms
        for (var q = 0; q < rooms.length; q++) {
            //Loop through the room pairings that haven't yet been checked
           ...