Here is a solution that I think works for no overlapping of segments.
You can modify segmentLenght and segmentNumber to what you need. You can also linke these to slider controllers for changing then easier.
var segmentLength = 10;
var segmentNumber = 100;
seedRandom(index, 1);
var lastIndex = 0;
Array.prototype.customIndexOf = function (element) {
for (var i = 0; i < this.length; i++) {
if (this[i][0] === element[0] && this[i][1] === element[1]) {
return i;
}
}
return -1;
};
function nextPoint() {
var crtPoint = points[lastIndex];
var movement = randomStr(freeDirections[lastIndex]);
freeDirections[lastIndex] = freeDirections[lastIndex].replace(movement, "");
doMovement(crtPoint, movement);
}
function doMovement(point, movement) {
var newPoint = point + move[movement];
myPath.push(newPoint);
if (points.customIndexOf(newPoint) == -1) {
lastIndex = points.length;
points.push(newPoint);
} else {
lastIndex = points.customIndexOf(newPoint);
}
if (freeDirections[lastIndex] == undefined) {
freeDirections[lastIndex] = "dulr".replace(opposite[movement], "");
} else {
freeDirections[lastIndex] = freeDirections[lastIndex].replace(opposite[movement], "");
}
}
function randomStr(str) {
return str[Math.floor(Math.random() * str.length)];
}
var move = {
"d": [0, 1],
"u": [0, -1],
"l": [-1, 0],
"r": [1, 0]
}
var opposite = {
"d": "u",
"u": "d",
"l": "r",
"r": "l"
}
//initialize the myPath
//first point has all the directions possible
freeDirections = ["dulr"];
//first point is [0,0], this is paired in indexes with the freeDirections array
var points = [[0, 0]];
//the points through which we went so far
var myPath = [[0, 0]];
for (var i = 0; i < segmentNumber; i++) {
nextPoint();
}
createPath(myPath.map(x => x * segmentLength), [], [], false);