JSFiddle - React, Tailwind, and code Playground

by francisfortier

JavaScript

COLS = Math.floor(window.innerWidth / 8);
ROWS = Math.floor(window.innerHeight / 8);

INFINITY = 0x7FFFFFFF;

TIMEOUT = 25;

var canvas = document.createElement("canvas");

canvas.setAttribute("width", COLS * 8 + "px");
canvas.setAttribute("height", ROWS * 8 + "px");

document.body.appendChild(canvas);

var ctx = canvas.getContext("2d");

function setDot(index, color) {
    var colIndex = index % COLS;
    var rowIndex = Math.floor(index / COLS);
    
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.moveTo(colIndex * 7 + 4, rowIndex * 7 + 4);
    ctx.arc(colIndex * 7 + 4, rowIndex * 7 + 4, 3, 0, Math.PI * 2, false);
    ctx.fill();
}

Array.prototype.contains = function(value) {
    for (var i = 0; i < this.length; i++)
    {
        if (this[i] === value)
        {
            return true;
        }
    }
    
    return false;
}
    
Array.prototype.pushIfNotIn = function(value, arr) {
    if (!arr.contains(value))
    {
        this.push(value);
    }
}

var walls = [];

for (var i = 0; i < 10; i++)
{
    var index = Math.floor(Math.random() * COLS * ROWS);
    
    if (Math.random() < 0.5)
    {
        var m = Math.min(Math.floor(Math.random() * COLS), COLS - index % COLS);
        
        for (var j = 0; j < m; j++)
        {
            walls.push(index + j);
            
            setDot(index + j, "#ffffff");
        }
    }
    else
    {
        var m = Math.min(Math.floor(Math.random() * ROWS), ROWS - Math.floor(index / COLS));
        
        for (var j = 0; j < m; j++)
        {
            walls.push(index + j * COLS);
            
            setDot(index + j * COLS, "#ffffff");
        }
    }
}

for (var i = 0; i < COLS * ROWS; i++)
{
    if (!walls.contains(i))
        setDot(i, "#c0c0c0");
}

var graph = [];

for (var i = 0; i < COLS * ROWS; i++)
{
    var edges = [];
    
    if (i % COLS > 0) edges.pushIfNotIn(i - 1, walls);
    if (i % COLS < COLS - 1) edges.pushIfNotIn(i + 1, walls);
    if (i > COLS) edges.pushIfNotIn(i - COLS,...