Piligrim

by evgkch

HTML

<canvas id='canvas'></canvas>

JavaScript

const sleep = time => new Promise(resolve => setTimeout(resolve, time));

const random = (from, to) => () => Math.floor(Math.random() * Math.abs(from - to));

function main(numberOfPoints, startPoint) {
	const canvas = document.getElementById('canvas');
  
  canvas.width = 512;
  canvas.height = 512;
  
  const ctx = canvas.getContext('2d');
  
  const origin = [canvas.width / 2, canvas.height / 2];
  
  const points = [];
  
  for (let i = 0; i < numberOfPoints; i++)
  {
  	const point = [
    	(Math.cos(2 * Math.PI * i / numberOfPoints) + 1) * origin[0],
      (Math.sin(2 * Math.PI * i / numberOfPoints) + 1) * origin[1]
    ];
    
    points.push(point);
  }
  
  points.forEach(point => {
  	ctx.beginPath();
    ctx.arc(point[0], point[1], 1, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();
  });
  
  const randomPoint = random(0, numberOfPoints);
  
  let piligrim = startPoint;
  
  function move(count) {
  	ctx.beginPath();
    const target = points[randomPoint()];
    console.log(piligrim)
    piligrim = [
    	(target[0] - piligrim[0]) / 2 + piligrim[0],
      (target[1] - piligrim[1]) / 2 + piligrim[1]
    ];
    ctx.arc(piligrim[0], piligrim[1], 1, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();
    
    sleep(0)
      .then(() => count > 0 ? move(--count) : null)
  }
  
  move(5)
}

main(5000, [0, 0])