Skip to content

Instantly share code, notes, and snippets.

@pcv2
Created January 23, 2012 03:42
Show Gist options
  • Save pcv2/1660394 to your computer and use it in GitHub Desktop.
Save pcv2/1660394 to your computer and use it in GitHub Desktop.
Simple Single Round Blackjack Game
// defines Card object
function Card(num, suit) {
this.num = num;
this.suit = suit;
}
// defines Deck object
function Deck() {
this.cards = new Array(52);
//this.next_card = 0;
for (i=1; i<14; i += 1) {
this.cards[i-1] = new Card(i, "clubs"); //creates suit of clubs for index 0-12
this.cards[i+12] = new Card(i, "hearts"); //creates suit of hearts
this.cards[i+25] = new Card(i, "spades");
this.cards[i+38] = new Card(i, "diamonds");
}
this.deal = deal;
this.hitMe = hitMe;
}
//defines method to add two initial cards to myHand
function deal(myHand) {
card1 = Math.floor( 52*Math.random() );
card2 = Math.floor( 52*Math.random() );
myHand[0] = this.cards[card1];
myHand[1] = this.cards[card2];
}
//defines method to add one addtional card to myHand
function hitMe(myHand) {
card = Math.floor( 52*Math.random() );
index = myHand.length;
myHand[index] = this.cards[card];
}
//defines total score of myHand
function score(hand) {
var total = 0;
var acesCount = 0; // this variable counts the number of aces in the hand.
var pips = 0; // num of card
for ( i=0; i<hand.length; i += 1 ) {
pips = hand[i].num;
if ( pips == 1) { // what to when you have an ace
acesCount += 1;
total += 11;
} else {
if ( pips == 11 || pips == 12 || pips == 13 ) {
total += 10;
} else {
total += pips;
}
}
}
while ( acesCount > 0 && total > 21 ) { // Count aces as 1 instead of 11 if over 21
total -= 10;
acesCount -= 1;
}
return total;
}
var myHand = new Array();
var deck = new Deck();
playRound();
function playRound() {
deck.deal(myHand);
count = score(myHand);
alert("You got "+count);
oneMore();
}
/* let's user determine to play for one more card and if still under 21 after
1 more card, let's user play again until at or over 21 */
function oneMore() {
var hit = confirm("Do you want another card?");
if (hit == true) {
deck.hitMe(myHand);
count = score(myHand);
if (count < 21) {
alert("you now have"+count)
oneMore();
} else if (count == 21) {
alert("You scored 21!");
} else {
alert("You've got "+count+". Should've quit while you were ahead!");
}
} else {
alert("it was nice playing with you!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment