37 lines
1017 B
Plaintext
37 lines
1017 B
Plaintext
function MovementSystem(grid, rules) {
|
||
var newmover = meme(MovementSystem_prototype)
|
||
newmover.grid = grid;
|
||
newmover.rules = rules || {}; // expects { canMove: fn }
|
||
newmover.turn = 'white';
|
||
return newmover
|
||
}
|
||
|
||
var MovementSystem_prototype = {
|
||
tryMove: function (piece, to) {
|
||
if (piece.colour != this.turn) return false;
|
||
|
||
// normalise ‘to’ into our hybrid coord
|
||
var dest = [to.x ?? t[0],
|
||
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 (length(victims) && victims[0].colour == piece.colour) return false;
|
||
if (length(victims)) 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
|