MooTools - ChessSquare Class
by pythondave
HTML
<div id="div1"></div>
CSS
#div1 table {
border-spacing: 0;
height: 30px;
}
#div1 td {
width: 30px;
height: 30px;
}
.blackSquare {
background-color: brown;
}
.whiteSquare {
background-color: yellow;
}
JavaScript
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 = {position:options}; }
this.position = options.position;
this.column = this.position.substr(0, 1).charCodeAt()-96;
this.row = Number(this.position.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;
}
});
new ChessSquare('a5').toElement().inject($('div1'));
new ChessSquare('a8').addPiece('r').toElement().inject($('div1'));
new ChessSquare('b8').addPiece('n').toElement().inject($('div1'));
new ChessSquare('b7').addPiece('p').toElement().inject($('div1'));
new ChessSquare('c1').addPiece('B').toElement().inject($('div1'));
new ChessSquare('d1').addPiece('Q').toElement().inject($('div1'));
new ChessSquare('e1').addPiece('K').toElement().inject($('div1'));