This game was created as a prototype to understand the capabilities of JavaScript and jQuery. All of the site and its entirety are here for your amusement or learning.
We need to first set up some basic variables. This sets up the deck and dealer and player hands.
suit = new Array('ofhearts', 'ofdiamonds', 'ofclubs', 'ofspades');
face = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
pickedCards = new Array();
playerCards = new Array();
dealerCards = new Array();
Next we need to do the first deal.
pickACard = function() {
//Draw a Card
cardSuit = suit[Math.floor(Math.random() * suit.length)];
cardFace = face[Math.floor(Math.random() * face.length)];
card = cardFace + cardSuit;
//Check if in pickedCards
while (card in check(pickedCards)) {
cardSuit = suit[Math.floor(Math.random() * suit.length)];
cardFace = face[Math.floor(Math.random() * face.length)];
card = cardFace + cardSuit;
}
return card;
}
This script is called 4 times in the beginning to pick the cards for both players, and then again if the player or dealer decides to hit.
Next we need to display the dealer's and player's hand.
playerDisplay = function() {
var playerStr = '';
for (var i = 0; i < playerCards.length; i++) {
playerStr += "<img src="images/cards/card-' + playerCards[i] + '.jpg" width="58" height="79" alt="player-cards" /> ';
}
document.getElementById("player").innerHTML = playerStr;
document.getElementById("player-score").innerHTML = "<strong>" + playerScoreFunc() + "</strong>";
}
Now we have the cards on the game window!
Now depending on what the player decides to click based on their hand, several scripts can fire. After each of these the game window gets updated.
If the player presses HIT, the script checks if the dealer needs another card and then gives the player a card.
If the player presses BET1 or BET5, the script makes sure the player has enough money and not over the bet limit, then places the bet
If the player presses STAY, the script checks if the dealer wants a card. If not, the game ends.
If the player presses HIT or STAY and either the player or dealer has busted or has hit blackjack the game is over.
Once the game has ended, the game engine decides who has won; If the player won it awards back their bet x 2, if not the bet is lost. The new game button is displayed and we restart.
If your still interested, instead of digging around in the site, below is the entire site zipped so you can try it yourself!
Download ZIP