Card Game Library
Note: this seems to only work in Chrome. Since this was just a hackathon project, we did not bother supporting any other browsers.
For the spring 2011 Berkeley CSUA hackathon two friends and I designed and implemented a library for easily creating JavaScript card games. The goal behind the library was simple: the library’s user should be able to focus only on the rules of the game without worrying about the underlying HTML, CSS and JavaScript.
I worked primarily on the abstractions in the library as well as the Klondike game. So the files I mostly wrote were {Card, Deck, Hand, Solitaire}.js. Jonathan Ewart worked on the actual UI code and the game of War and Valerie Woolard worked on the graphics and visual design.
We ended up getting 2nd place at the hackathon and winning Kindles, which was nice.
The Klonide source: [show]
/**
* A game of Klondike Solitaire.
*/
function Solitaire() {
var board = new Board({
rootId : "Klondike",
magicalX : 106
});
var totalDeck = new Deck(board.collapsedType, 0, 0, {
//never let someone drag a card to the deck
filter : function () { return false; },
draggable : false
});
totalDeck.initialize(true);
var discard = new Deck(board.collapsedType, 1, 0, {
filter : function(card) { return false; }
});
board.addDeck(discard);
totalDeck.shuffle();
totalDeck.setAction(function () {
var top = totalDeck.peek();
if (!top) {
discard.deal(totalDeck, discard.getCards().length, true);
} else {
top.setFaceUp(true);
totalDeck.remove(top);
discard.addTop(top);
}
});
board.addDeck(totalDeck);
var pile;
var endPiles = [];
for (var i = 1; i <= 7; i++) {
pile = new Deck(board.defaultType, i - 1, 1);
totalDeck.deal(pile, i, true);
var topCard = pile.peek();
if (topCard) {
topCard.setFaceUp(true);
}
pile.setFilter((function (pile) {
return function (card) {
var top = pile.peek();
if (top) {
return (top.getColor() != card.getColor()) &&
top.getRank() - card.getRank() ==1;
} else {
return card.getRank() == 13;
}
};
})(pile));
// Flip the top card if needed:
pile.observe((function (pile) {
return function (event) {
if (event.type == "remove") {
if (pile.peek()) {
pile.peek().setFaceUp(true);
}
}
};
})(pile));
board.addDeck(pile);
}
for (i = 0; i < 4; i++) {
endPiles[i] = new Deck(board.collapsedType, 3 + i, 0);
board.addDeck(endPiles[i]);
endPiles[i].setFilter((function (pile) {
return function (card, deck, size) {
if (size > 1) {
return false;
}
var top = pile.peek();
if (top) {
return (top.getSuit() == card.getSuit()) &&
(card.getRank() - top.getRank() == 1);
} else {
return card.getRank() == 1;
}
};
})(endPiles[i]));
}
}
$(document).ready(function() { new Solitaire(); });
[show]
You can get the full source on Google Code.