I would like to generate a random path from the top to bottom of a matrix.
Requirements:
- The path can wind around, but it must connect from row 1 to the last row.
- Eventually, I'd like the colors to be random for each path piece, but for now it can be uniform (I've tested below with just red)
- Paths connecting from top to bottom are randomly generated
- The path pieces obviously must connect, and shouldn't fork (aka, give player 2 options to choose to go, shown here)
- The path can only go from top to bottom (cannot move back up), but it can wind left and right

What I've considered:
- I can't simply check if the above row's column is part of the path, because then it will continuously generate path pieces when it finds the first true value.
- I'm not interested in generating paths manually, as that would require a new matrix specifying 1's and 0's where I want the path to go. And then for each "random" path option, I would have to build a new matrix. More importantly, manually generating path in matrices would make scaling the matrix size far more tedious... For example If I changed my 6x6 matrix to a 100x100.
So yeah, the easy way would be to just make this and iterate through it:
var matrixPaths = [
[0,1,0,0,0,0],
[0,1,1,1,0,0],
[0,0,0,1,0,0],
[0,0,0,1,1,1],
[0,0,0,0,0,1],
[0,0,0,0,0,1]
];
On the left, empty grid, on the right, what it should generate

My thought was to first create the grid and add the spans in each matrix entry:
function createMyGrid() {
//create 6x6 matrix
for(var i=1; i<=6; i++) {
matrix[i] = [];
for(var j=1; j<=6; j++) {
var colorIndex = Math.floor(Math.random() * (color.length - 0) + 0);
var $span = $('<span />').attr('class', 'colorSquare').html("[" + i + "][" + j + "]");
$("#grid").append($span);
matrix[i][j] = $span;
}
}
}
Then, generate the first path piece at random in row 1. Then for each subsequent row, check for a path piece above it to connect... then from that piece, start generated the next set:
function createPath() {
var randomColumn = Math.floor(Math.random() * (matrix[1].length - 0) + 0);
matrix[1][randomColumn].data('partOfPath', true);
matrix[1][randomColumn].addClass("red");
for (var row = 2; row <= 6; row++) {
for (var col = 1; col <= 6; col++) {
if (matrix[row-1][col].data('partOfPath')) { //if block above is partOfPath... add a set of items of random # of columns across
addRowPath(row, col);
}
}
}
}
function addRowPath (row, pathCol) { //need to start offset from that row/col position,
var randRowPathLength = Math.floor(Math.random() * (matrix[row].length - 0) + 0);
for (var col = pathCol; col <= randRowPathLength; col++) {
matrix[row][col].addClass("red");
}
}
So far it's adding the initial step, then the row below, but then stopping.

console.log()calls at various points to see what the values are and why the path is ending, or put a breakpoint in your code and step through it line by line until you figure it out. This is what debugging is. - user1106925