>Wouldn't it have been easier to have the cards as DOM objects that you
move about? Then you only need deal with position, z-index and
display/visibility so no messing with HTML at all.
Rob,
actually that is what I have done, but to deal with the card logic of
shuffling the deck and dealing the cards its easiers when they are in a
more pure form. Only worrying about the card image once it needs to be
displayed.
To create a deck I use this function:
function Deck () {
var S,N,A,j,i,v;
S=["H","D","C","S"];
N=[2,3,4,5,6,7,8,9,10,"J","Q","K","A"];
A= new Array();
for(j=0;j<S.length;j++)
{
for(i=0;i<N.length;i++)
{
v = (i >= 8)?( (i == 12)? 1 : 10 ): N[i];
A[A.length]= {suit: S[j], card:N[i],val:v};
}
}
return A;
}
I have a Game object:
function Game () {
var self = this;
this.type = 'blackjack';
this.you = new Player(this,'you');
this.dealer = new Player(this,'dealer');
this.deck = Deck();
}
which contains my deck and player objects and to shuffle I do:
Game.prototype.shuffle= function(times){
var i,j,t,v,l=this.deck.length;
while(times--){
with(Math){i=floor(random()*l);j=floor(random()*l) ;}
t=this.deck[i];this.deck[i]=this.deck[j];this.deck[j]=t;
}
return this.deck;
}
And calculating player hand is much easier with the array like so:
Player.prototype.Calculate = function() {
var t=0,a=0,i,h=this.hand,l=this.hand.length,v=new Array();
for (i=0;i<l;i++){
if (h[i].val != 1) t += h[i].val;
else { a++ }
}
if ( a > 0 ) t = ( (t+(a-1)+11)>21)?(t+a):(t+(a-1)+11);
return t;
}
finally to render a card I just do:
function _toCard (suit, card) {
var c, s,html,top,bottom,glyph;
switch (suit)
{
case 'H': c = 'red'; s = '\u2665'; break;
case 'D': c = 'red'; s = '\u2726'; break;
case 'C': c = 'black'; s = '\u2663'; break;
case 'S': c = 'black'; s = '\u2660'; break;
}
html = document.createElement('DIV');
html.className = 'card '+c;
top = document.createElement('DIV');
top.appendChild( document.createTextNode( card ) );
top.className = 'top';
html.appendChild( top );
glyph = document.createElement('DIV');
t = document.createTextNode(s);
glyph.appendChild( t );
glyph.className = 'suit';
html.appendChild( glyph );
bottom = document.createElement('DIV');
bottom.appendChild( document.createTextNode( card ) );
bottom.className = 'bottom';
html.appendChild( bottom );
return html;
}
I am not saying it is perfect but it seperates presentational logic,
and allowed me to accomplish a full blackjack game with css/js/html in
under 8k.