As someone new to programming, I am building a chess web application in JavaScript, both for fun and to learn more about design patterns. I keep running into a wall, which is how to decompose the program.
To start, I have picked a straightforward representation of a chessboard, here:
Board = function() {
var turn = 0;
var model = [[-4, -2, -3, -5, -6, -3, -2, -4],
[-1, -1, -1, -1, -1, -1, -1, -1],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 1, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1, 1, 1],
[ 4, 2, 3, 5, 6, 3, 2, 4]];
with some basic access routines, such as
this.move = function(pt1, pt2) {
turn += 1;
model[pt2.x][pt2.y] = model[pt1.x][pt1.y];
model[pt1.x][pt1.y] = 0;
};
...
It makes sense that the board encapsulates state and is responsible for changing state but may not know the rules of the game--I like the idea of being able to plug in some sort of RulesContoller
and completely change the nature of the game at runtime. But beyond that, I'm a little paralyzed as to how granular to model the pieces. I see a few options.
First, I could define a Piece
constructor and instantiate a new piece for each index in the nested array, something like:
_.each(state, function(row, y) {
_.each(row, function(val, x) {
state[y][x] = new Piece(x, y, val);
});
});
Piece
could easily deduce its color, type (e.g. 'king'), and location from that information. But it also feels redundant, since I'm just translating a model that already completely represents the board. Also, it doesn't seem like the primary purpose of the Piece
'class' is this translation, e.g. "Oh, I'm a -5, must be a dark Queen."
Another option is to make the pieces dumber, i.e. not able to deduce this information from the model. But then I just build the array in-line, like
var model = [new Rook(1,1,'dark'), new Knight(1,2,'dark'), new Bishop(1,3,'dark')... ],
...
This seems closer to the way a chessboard is actually setup: there isn't some elegant formula; rather, you just put pieces in their correct location. But it's also just brute force. There are a few symmetries involved and patterns that might be simplified.
Anyway, I'm just spitballing at this point. Any ideas would be useful. Thanks.