Skip to content

Instantly share code, notes, and snippets.

@benbenbenbenbenben
Last active February 5, 2016 11:44
Show Gist options
  • Save benbenbenbenbenben/5dd66310ab992cbea373 to your computer and use it in GitHub Desktop.
Save benbenbenbenbenben/5dd66310ab992cbea373 to your computer and use it in GitHub Desktop.
var Slots = (function(options) {
this.mode = 'x';
this.max = options.width;
if (options.height) {
this.mode = 'y';
this.max = options.height;
}
this.grid = 0;
this.items = [];
});
Slots.prototype = {
shapeToArray: function(x, y) {
if (this.mode == 'x') {
if (x > this.max)
throw 'x exceeds max width';
} else {
if (y > this.max)
throw 'y exceeds max height';
var _y = x;
var _x = y;
x = _x;
y = _y;
}
var a = [];
while (y-- > 0) {
var m = this.max;
var px = x;
while (px-- > 0) {
a.push(1);
m--;
}
while (m-- > 0) {
a.push(0);
}
}
return a;
},
peek: function(x, y) {
var shape = this.shapeToArray(x, y);
var width = this.mode == 'x' ? x : y;
var movement = this.max - width;
var gridi = this.grid;
var shapestr = shape.toString().replace(/,/g, '').match(/.*1/)[0];
var slen = shapestr.length;
var shapei = parseInt(shapestr, 2);
var c = 0;
while (true) {
// var ok = ((grid ^ shape << q) & grid) == grid;
for (var i = c; i <= movement + c; i++) {
if (i + slen >= 32) {
throw 'overflow, cannot fit shape';
}
var ok = ((gridi ^ shapei << i) & gridi) == gridi;
if (ok) {
var yi = (i / this.max)|0;
var xi = (i % this.max);
if (this.mode == 'x')
return { x: xi, y: yi, i: i, shape: shapei };
else
return { x: yi, y: xi, i: i, shape: shapei };
}
}
c += this.max;
}
},
add: function(x, y) {
var peek = this.peek(x, y);
this.items.push(peek);
this.grid = this.grid | (peek.shape << peek.i);
return peek;
}
};
if (typeof(module) != "undefined")
module.exports = Slots;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment