function bg(colr='white') {
  g_ctx.fillStyle=colr;
  g_ctx.fillRect(0,0,g_side,g_side);
}
function bk(t,d) {
  fd(t,-d);
}
function cs() {
  g_ctx.clearRect(0,0,g_side,g_side);
}
function fd(t,d) {
  g_ctx.strokeStyle=t.colr;
  g_ctx.lineWidth=t.width;
  g_ctx.beginPath();
  g_ctx.moveTo(t.x*g_step,t.y*g_step);
  var rad=t.h*Math.PI/180.0;
  var dx=d*Math.sin(rad);
  var dy=-d*Math.cos(rad);
  t.x=t.x+dx; t.y=t.y+dy;
  if (t.pen=='down') {
    g_ctx.lineTo(t.x*g_step,t.y*g_step);
  } else {
    g_ctx.moveTo(t.x*g_step,t.y*g_step);
  }
  g_ctx.stroke();
}
function home(t) {
  t.x=400; t.y=400; t.h=0;
}
function join(t1,t2) {
  g_ctx.beginPath();
  g_ctx.moveTo(t1.x*g_step,t1.y*g_step);
  g_ctx.strokeStyle=t1.colr;
  g_ctx.lineWidth=t1.width;
  g_ctx.lineTo(t2.x*g_step,t2.y*g_step);
  g_ctx.stroke();
}
function lt(t,angle) {
  rt(t,-angle);
}
function pc(t,colr='black') {
  t.colr=colr;
}
function pd(t) {
  t.pen='down';
}
function points(n) {
  var t=turtle();
  home(t); pu(t);
  var x=[]; var y=[];
  var angle=360/n; var d=350;
  for (var i=0;i<n;i++) {
    fd(t,d); x.push(t.x); y.push(t.y);
    bk(t,d); rt(t,angle);
  }
  return {x:x, y:y};
}
function pu(t) {
  t.pen='up';
}
function pursuit(n) {
  var colrs=['red','orange','yellow','lime','lightblue','violet','cyan','magenta','pink','khaki'];
  bg('black');
  var pts=points(n);
  var t=[];
  for (var i=0; i<n; i++) {
    t[i]=turtle();
    t[i].x=pts.x[i];
    t[i].y=pts.y[i];
  }
  for (var j=0;j<1000;j++) {
    for (var i=0; i<n; i++) {
      var k=i+1;
      if (k==n) k=0;
      var cn=i%colrs.length;
      towards(t[i],t[k]);
      pc(t[i],colrs[cn]);
      join(t[i],t[k]);
      fd(t[i],g_d);
    }
  }
}
var g_d=1;
function pursuits(n=3) {
  clearTimeout(g_timer);
  pursuit(n);
  n++;
  if (n<13) {
    g_timer=setTimeout(pursuits,2000,n);
  } else {
    if (g_d==1) {
      g_d=20; n=3;
      g_timer=setTimeout(pursuits,2000,n);
    }
  }
}
function resize() {
  var side=75*vmin();
  if (side!=g_side) {
    setup();
  }
}
function rt(t,angle) {
  t.h=t.h+angle;
  t.h=t.h%360;
}
function setup() {
  g_side=75*vmin();
  var canvas=document.getElementById('c');
  canvas.width=g_side; canvas.height=g_side;
  g_ctx=canvas.getContext('2d');
  g_step=g_side/800;
}
// set t1's heading towards t2
function towards(t1,t2) {
  var x1=t1.x; var y1=t1.y;
  var x2=t2.x; var y2=t2.y;
  var dx=x2-x1; var dy=y1-y2;
  if (dy==0) {
    var h=90*Math.sign(dx);
  } else {
    var rad=Math.atan(dx/dy);
    var h=rad*180/Math.PI;
    if (dy<0) h=180+h;
    if (dx<0 && dy>0) h=360+h;
  }
  t1.h=h;
}
function turtle (colr='black') {
  var t={}; // associative array
  t.colr=colr;
  t.x=400; t.y=400; t.h=0;
  t.width=2; t.pen='down';
  return t;
}
function vmin() {
  var w=innerWidth; var h=innerHeight;
  var v=w;
  if (h<w) v=h;
  return v/100;
}
