Dealing Cards Array Simulation

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

by Ron Eaglin

HTML

<input type="button" value="Deal Card" id="deal" />
<br/>
<br/>
<div id='drop' class='drop'>Drop Here</div>

CSS

.drop {
 
    float: left;
    width: 300px;
    height: 200px;
    background-color: pink;
}

JavaScript

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

function init() {
  $('.drop').droppable( {
    drop: handleDropEvent
  } ); 
    }

var cardsInDeck = new Array();
var numberOfCardsInDeck = 9;
cardsInDeck[0] = "10Spades";
cardsInDeck[1] = "2Spades";
cardsInDeck[2] = "4Clubs";
cardsInDeck[3] = "5Hearts";
cardsInDeck[4] = "6Spades";
cardsInDeck[5] = "8Diamonds";
cardsInDeck[6] = "9Hearts";
cardsInDeck[7] = "JackDiamonds";
cardsInDeck[8] = "KingSpades";

function dealCard(i) {
    if (numberOfCardsInDeck == 0) return false;
    var img = document.createElement("img");
    img.src = "https://amberthomaswebdesign.com/carddealing/" + cardsInDeck[i] + ".png";
    img.width = '100';
    $(img).draggable();

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

function randomCard() {
   return Math.floor(Math.random() * numberOfCardsInDeck);  
}
 function handleDropEvent( event, ui ) {
  var draggable = ui.draggable;
 alert( 'The card with ID "' + draggable.attr('id') + '" was dropped onto me!' );
    
 }

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--;
}