Dealing Cards Array Simulation

Shows how to create an array of playing cards and deal randomly from the array.

by Kristy Bond

HTML

<input type="button" value="Deal Card" id="deal" />

JavaScript

$('#deal').click(function () {
    dealCard(randomCard());
});

var cardsInDeck = new Array();
var numberOfCardsInDeck = 5;
cardsInDeck[0] = "ace_of_hearts";
cardsInDeck[1] = "2_of_clubs";
cardsInDeck[2] = "ace_of_clubs";
cardsInDeck[3] = "king_of_diamonds";
cardsInDeck[4] = "jack_of_spades";

function dealCard(i) {
    if (numberOfCardsInDeck == 0) return false;
    var img = document.createElement("img");
    img.src = "http://kristybond.com/cards/" + cardsInDeck[i] + ".png";

    document.body.appendChild(img);
    removeCard(i);
}

function randomCard() {
   return Math.floor(Math.random() * numberOfCardsInDeck);  
}

function removeCard(c)
{
    // simply make every higher numbered card move down 1
    for (j=c; j <= numberOfCardsInDeck - 2; j++)
    {
        cardsInDeck[j] = cardsInDeck[j+1];
    }
    numberOfCardsInDeck--;
}

$( init );
 
function init() {
  $('#makeMeDraggable').draggable();
  $('#makeMeDroppable').droppable( {
    drop: handleDropEvent
  } );
}
 
function handleDropEvent( event, ui ) {
  var draggable = ui.draggable;
  alert( 'The square with ID "' + draggable.attr('id') + '" was dropped onto me!' );
}