Skip to content

Instantly share code, notes, and snippets.

@andresilva
Created December 7, 2013 00:08
Show Gist options
  • Save andresilva/7834965 to your computer and use it in GitHub Desktop.
Save andresilva/7834965 to your computer and use it in GitHub Desktop.
function invert(move) {
switch (move) {
case 'up': return 'down';
case 'down': return 'up';
case 'left': return 'right';
case 'right': return 'left';
default: return move;
}
}
function orthogonal(move) {
switch (move) {
case 'up': return 'left';
case 'down': return 'left';
case 'left': return 'up';
case 'right': return 'up';
default: return move;
}
}
var previousMove;
var previousDistance;
var blacklist = {};
var state = 0;
function tick(distance) {
if (distance === 0) {
return '';
}
var move;
switch (state) {
case 0:
move = 'up';
state = 1;
break;
case 1:
if (distance < previousDistance) {
move = previousMove;
} else {
blacklist[previousMove] = true;
move = invert(previousMove);
state = 2;
}
break;
case 2:
move = orthogonal(previousMove);
if (move in blacklist) {
move = invert(move);
}
state = 3;
break;
case 3:
if (distance < previousDistance) {
move = previousMove;
state = 1;
} else {
move = invert(previousMove);
state = 4;
}
break;
case 4:
move = previousMove;
state = 1;
break;
default:
}
previousDistance = distance;
previousMove = move;
return move;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment