MooTools - ChessBoard Class

by pythondave

HTML

<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
<div id="div5"></div>

CSS

div {
    margin: 0 0 20px 0;
}

table {
    border-spacing: 0;
}

table tr td img {display:block; margin: 0 auto;}

td {
    width: 40px;
    height: 40px;
}

.blackSquare {
    background-color: BurlyWood;
}

.whiteSquare {
    background-color: Cornsilk;
}

JavaScript

//WIP

Array.implement('pushN', function(object, number) {
    for (var i = 0; i < number; i++) { this.push(object); }
    return this;
});

var ChessPiece = new Class({
    initialize: function(options) {
        if (typeof(options) == 'string') { options = { type: options }; }
        this.type = options.type; //'r': black rook, 'R': white rook, ...
        this.colour = (this.type == this.type.toUpperCase()) ? 'w' : 'b';
        this.imgRoot = 'http://www.chessguru.de/palview/linpcs35/';
        this.imgSrc = this.imgRoot + this.colour + this.type.toLowerCase() + '35.gif';
        this.element = new Element('img', { src: this.imgSrc });
    },
    toElement: function() { return this.element; }
});

var ChessSquare = new Class({
    initialize: function(options) {
        if (typeof(options) == 'string') { options = { location: options }; }
        this.location= options.location; //'a8','b8',...,'h1'
        this.column = this.location.substr(0, 1).charCodeAt() - 96;
        this.row = Number(this.location.substr(1, 1));
        this.colour = ((this.row + this.column) % 2 == 1) ? 'w' : 'b';
        this.cssClass = (this.colour == 'w') ? 'whiteSquare' : 'blackSquare';
        this.element = new Element('td', { 'class': this.cssClass });
    },
    toElement: function() { return this.element; },
    addPiece: function(options) {
        this.piece = new ChessPiece(options);
        this.element.empty().grab(this.piece.toElement());
        return this;
    },
    hasPiece: function() { return typeof(this.piece) != 'undefined' }
});

var ChessBoard = new Class({
    Implements: Options,
    options: {
        fen: 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1' //initial position
    },
    initialize: function(options) {
        if (typeof(options) == 'string') { options = { fen: options }; }
        this.setOptions(options);
        this.squares = this.squaresFromFen(this.options.fen); //array of 64 square objects
        this.element =...