Skip to content

Instantly share code, notes, and snippets.

@geoffreyd
Created February 1, 2011 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geoffreyd/805576 to your computer and use it in GitHub Desktop.
Save geoffreyd/805576 to your computer and use it in GitHub Desktop.
app.get('/move/:from/:to', function(req, res) {
console.log("Move");
// Define the 'board' parameter here.
board.load(function(board) {
from = req.params.from
to = req.params.to
// The scope of `this is far too finicky, it's always better to
// try another option if you can. In this case
res.send({removed: board.move(from, to)})
});
});
--------------------------------------
board.js
var fs = require('fs');
module.exports = {
pieces: {}
, create: function () {
this.buildBackRow("1", "W");
this.buildPawnRow("2", "W");
for (var col = 3; col <= 6; col ++) {
this.buildBlankRow(col)
}
this.buildPawnRow("7", "B");
this.buildBackRow("8", "B");
this.save();
return this.pieces;
}
, buildBackRow: function (row, color) {
for (var col = 0; col < 8; col ++) {
this.pieces[this.col_labels[col] + row] = color + this.row_pieces[col];
}
}
, buildPawnRow: function (row, color) {
for (var col = 0; col < 8; col ++) {
this.pieces[this.col_labels[col] + row] = color + "P";
}
}
, buildBlankRow: function (row) {
for (var col = 0; col < 8; col ++) {
this.pieces[this.col_labels[col] + row] = "";
}
}
, col_labels: ["a", "b", "c", "d", "e", "f", "g", "h"]
, row_pieces: ["R", "N", "B", "Q", "K", "B", "N", "R"]
, save: function () {
fs.writeFileSync("board.hash", JSON.stringify(this.pieces));
}
, load: function (callback) {
fs.readFile('board.hash', function(err, data) {
if (err) {
console.log("Missing");
this.pieces = {};
}
else {
this.pieces = JSON.parse(data);
}
// Pass in the board to the callback, so that it can work on it.
// This will become the `board` parameter up the top.
callback(this);
});
}
, move: function (from, to) {
console.log("here");
piece = this.pieces[from]
this.pieces[from] = "";
removed = this.pieces[to]
this.pieces[to] = piece;
return removed;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment