JSFiddle - React, Tailwind, and code Playground
HTML
<p>Click on a row to show the path</p>
<canvas id="canvas" width="450" height="350"></canvas>
<textarea id="output" style="width:100%; height:24em;"></textarea>
JavaScript
var WIDTH = 20,
HEIGHT = 15,
JUNCTIONS = [],
PROBABILITY = 0.2,
COLOR1 = '#00DD00',
COLOR2 = '#DD0000',
RADIUS = 4,
SPACING = 20,
turns = 0,
pipe = 10,
canvas,
context;
function Junction( x, y ){
this.x = x;
this.y = y;
this.l = null;
this.r = null;
if ( y == 0 )
JUNCTIONS[x] = [];
JUNCTIONS[x][y] = this;
var l = this.left();
if ( x > 0 && l.l == null && Math.random() <= PROBABILITY )
{
this.l = l;
l.r = this;
}
}
Junction.prototype.left = function(){
return this.x == 0?null:JUNCTIONS[this.x-1][this.y];
}
Junction.prototype.right= function(){
return this.x == WIDTH-1?null:JUNCTIONS[this.x+1][this.y];
}
Junction.prototype.down = function(){
return this.y == HEIGHT-1?null:JUNCTIONS[this.x][this.y+1];
}
Junction.prototype.reset = function(){
this.entry = null;
this.exit = null;
}
Junction.prototype.followPipe = function( prev ){
this.entry = prev;
if ( prev === this.l || prev === this.r ) {
this.exit = this.down() || true;
turns++;
} else if ( this.l !== null ) {
this.exit = this.l;
turns++;
} else if ( this.r !== null ) {
this.exit = this.r;
turns++;
} else
this.exit = this.down() || true;
console.log( this.exit );
if ( this.exit !== true )
this.exit.followPipe( this );
}
Junction.prototype.toString = function(){
if ( this.entry === null ){
if ( this.r === null ) return '| ';
return '|--';
} else {
if ( this.r === null ) return ': ';
return ':==';
}
}
function init(){
for ( var x = 0; x < WIDTH; ++x )
for ( var y = 0; y < HEIGHT; ++y )
new Junction( x, y );
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
canvas.addEventListener('click', draw );
draw();
}
function draw( evt ){
for ( var x = 0; x < WIDTH; ++x )
for ( var y = 0; y < HEIGHT; ++y )
JUNCTIONS[x][y].reset();
if ( evt ){
pipe = Math.round((evt.clientX - canvas.getBoundingClientRect().left)/SPACING)-1;
if ( pipe < 0 ) pipe = 0;
if (...