Skip to content

Instantly share code, notes, and snippets.

@sarahob
Created January 28, 2017 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarahob/5b26ac4e85150877e8dd50cb36162242 to your computer and use it in GitHub Desktop.
Save sarahob/5b26ac4e85150877e8dd50cb36162242 to your computer and use it in GitHub Desktop.
Random Walker

Random Walker with D3.js.

Allow path to walk until it reaches the bounds of the svg. Use random number to determine direction, then update path data. Inspired by Coding Train Coding Challenge

<html>
<head></head>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = 1000,
height = 1000,
startX = width / 2,
startY = height / 2,
i = 0, // use i to track current point
walking,
svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.style('background-color', 'steelblue'),
renderPath = d3.line()
.x(function(d) {
return d.x;
})
.y(function(d) {
return d.y;
}),
path = svg.append('path')
.datum([{
x: startX,
y: startY
}])
.attr('stroke-width', 2)
.attr('stroke', '#fff')
.attr('fill', 'none');
init();
//set first movement, initiate walker
function init() {
path.datum().push({
x: (startX + 1),
y: startY
});
path.attr('d', renderPath);
walking = setInterval(function() {
pathwalker();
}, 10);
}
function pathwalker() {
i++; //increment i
var r = getRandomNumber(1, 4),
d = path.datum()[i], //always use most recent datum to find current point
p = {
x: 0,
y: 0
};
if (r === 1) {
//go up
p.x = d.x;
p.y = d.y - 10;
} else if (r === 2) {
//go right
p.x = d.x + 10;
p.y = d.y;
} else if (r === 3) {
//go down
p.x = d.x;
p.y = d.y + 10;
} else if (r === 4) {
//go left
p.x = d.x - 10;
p.y = d.y;
}
//if goes out of bounds stop walker
if (p.x > width || p.x < 0 || p.y > height || p.y < 0) {
console.log('OUT OF BOUNDS!');
clearInterval(walking);
}
path.datum().push(p);
path.attr('d', renderPath);
};
//util: get random number between 2 inputs
function getRandomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment