Skip to content

Instantly share code, notes, and snippets.

@FrancoB411
Created March 28, 2012 08:42
Show Gist options
  • Select an option

  • Save FrancoB411/2224810 to your computer and use it in GitHub Desktop.

Select an option

Save FrancoB411/2224810 to your computer and use it in GitHub Desktop.
Blackjack game from week 12 of CodeYear
function Card(suit, num) {
var cardSuit = suit;
var cardNum = num;
this.getNumber = function() {
return cardNum;
};
this.getSuit = function() {
return cardSuit;
};
this.getValue = function() {
var score;
if(cardNum >10 && cardNum <14) {
score = 10;
}else if(cardNum === 1) {
score = 11;
}else {
score = cardNum;
}
return score;
};
}
function deal() {
var suit = Math.floor(Math.random()*4+1);
var num = Math.floor(Math.random()*13+1);
var newCard = new Card(suit, num);
return newCard;
}
function Hand() {
var cards =[];
cards.push(deal());
cards.push(deal());
this.getHand = function() {
return cards;
};
this.score = function() {
var sum = 0;
var aces = 0;
for (i=0; i<cards.length; i++) {
sum += cards[i].getValue();
if(cards[i].getValue == 11){
aces += 1;
}
}
while(sum > 21 && aces >= 0){
sum -= 10;
aces -= 1;
}
return sum;
};
this.stringSuit = function(num) {
switch(num)
{
case 1:
return "Diamonds";
break;
case 2:
return "Hearts";
break
case 3:
return "Spades";
break;
case 4:
return "Clubs";
break;
}
};
this.printHand = function() {
var hand = [];
for(i=0; i<cards.length; i++) {
hand.push(" "+ cards[i].getNumber() + " of " + this.stringSuit(cards[i].getSuit()) );
}
return hand;
};
this.hitMe = function() {
cards.push(deal());
};
}
function playAsDealer() {
var dHand = new Hand();
var dScore = dHand.score();
while(dScore <= 17) {
dHand.hitMe();
dScore = dHand.score();
}
return dHand;
}
function playAsUser() {
var pHand = new Hand();
var pHit = confirm(pHand.printHand());
while(pHit === true) {
pHand.hitMe();
pHit = confirm(pHand.printHand());
}return pHand;
}
function declareWinner(userHand, dealerHand) {
var userScore = userHand.score();
var dealerScore = dealerHand.score();
if (dealerScore > 21){
return "You win!";
}else if (userScore >21) {
return "You lose!";
}else if (userScore > dealerScore) {
return "You win!";
}else if (userScore < dealerScore) {
return "You lose!";
}else{
return "You tied!";
}
}
function playGame() {
var user = playAsUser();
var dealer = playAsDealer();
console.log("Your score is " + user.score() + ".");
console.log("Dealer's score is " + dealer.score() + ".");
console.log(declareWinner(user, dealer));
}
playGame();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment