33 lines
996 B
Plaintext
33 lines
996 B
Plaintext
var MovementSystem = function(grid, rules) {
|
||
this.grid = grid;
|
||
this.rules = rules || {}; // expects { canMove: fn }
|
||
this.turn = 'white';
|
||
}
|
||
|
||
MovementSystem.prototype.tryMove = function (piece, to) {
|
||
if (piece.colour !== this.turn) return false;
|
||
|
||
// normalise ‘to’ into our hybrid coord
|
||
var dest = [to.x !== undefined ? to.x : to[0],
|
||
to.y !== undefined ? to.y : to[1]];
|
||
|
||
if (!this.grid.inBounds(dest)) return false;
|
||
if (!this.rules.canMove(piece, piece.coord, dest, this.grid)) return false;
|
||
|
||
var victims = this.grid.at(dest);
|
||
if (victims.length && victims[0].colour === piece.colour) return false;
|
||
if (victims.length) victims[0].captured = true;
|
||
|
||
this.grid.remove(piece, piece.coord);
|
||
this.grid.add (piece, dest);
|
||
|
||
// grid.add() re-creates coord; re-add .x/.y fields:
|
||
piece.coord.x = dest.x;
|
||
piece.coord.y = dest.y;
|
||
|
||
this.turn = (this.turn === 'white') ? 'black' : 'white';
|
||
return true;
|
||
};
|
||
|
||
return { MovementSystem: MovementSystem };
|