Skip to content

Instantly share code, notes, and snippets.

@eush77
Created June 26, 2014 10:49
Show Gist options
  • Save eush77/9ad5343c67b0aef9f0b2 to your computer and use it in GitHub Desktop.
Save eush77/9ad5343c67b0aef9f0b2 to your computer and use it in GitHub Desktop.
Helper function for Bit's Quest (bitsquest.bitbucket.org) that launches callbacks in a sequence
var phase = 0;
var bounce = (function () {
var nextPhaseToAssign = 0;
var opposite = {
top: 'bottom',
left: 'right',
bottom: 'top',
right: 'left'
};
return function assign(direction) {
if (!direction) {
return;
}
var customHandler;
if (Array.isArray(direction)) {
customHandler = direction[1];
direction = direction[0];
}
var myPhase = nextPhaseToAssign++;
this.on('sensor:' + direction, function (contact) {
if (contact && phase == myPhase) {
if (customHandler) {
customHandler.call(this);
}
else {
// Default handler.
this.thrusters[opposite[direction]](false);
this.thrusters[direction](true);
}
phase += 1;
}
});
assign.apply(this, [].slice.call(arguments, 1));
}.bind(this);
}.call(this));
// Example: solution for #5 "Going Up"
// http://bitsquest.bitbucket.org/index.html#5
this.on('start', function () {
this.thrusters.left(true);
this.thrusters.top(true);
});
bounce('bottom',
'right',
'top',
'left',
'bottom',
'right',
'top',
['bottom', function () {
this.thrusters.right(false);
this.thrusters.top(false);
this.thrusters.left(true);
this.thrusters.bottom(true);
}]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment