4
\$\begingroup\$

I am currently learning JavaScript and the project I have been working on is creating a basic Blackjack game. Some code was provided for me, with the additional instructions:

"How would you edit the above code to PRINT what you and the Dealer have? How would you edit the code to let you know if you beat the dealer or not? How would you edit the code to let you know who busted? Hit 21? Also, would you hit once? Twice? What code would you put in if you hit either way? Test and run your code in an IDE of your choice."

The code I completed does work, but I believe there is probably a smarter way to write it. My code is as follows:

/* Created by Michael on 5/18/2016. */
// ——- —— —  
// INPUTS: Two Integers
// OUTPUT: an Integer
// EFFECT: Returns a random integer between two inputs
function randint( min, max) {
    return Math.floor( Math.random() * (max - min + 1) + min);
}

// INPUTS: none
// OUTPUT: none
// EFFECT: "Player gets a Card"
 function hitMe() {
    console.log(" Hit me." );
handValue += randint( 1,11);
console.log(" New Hand: " + handValue)
}

// These are the cards you have
// your HandValue is an Integer
var handValue = 0;



// These are the cards the Dealer has
// the DealerValue is an Integer
var dealerValue = 0;



// here are your first two cards
handValue += randint( 1,11);
handValue += randint( 1,11);


// here are the Dealers cards
dealerValue += randint( 1,11);
dealerValue += randint( 1,11);


// the Dealer always hits once
dealerValue += randint( 1,11);
console.log("Dealer hits, do you hit or call?");

console.log("hit or call?");


if (handValue < 18)
{
    hitMe()
}
    if (handValue < 18) {
        hitMe()
    }
        if (handValue > 21) {
        console.log("Player Busts! Dealer has " + dealerValue + ".")
    } else if (handValue == 21) {
        console.log("Player hit 21! Dealer has " + dealerValue + ".")
    } else if (dealerValue == 21) {
        console.log("Dealer hit 21! Player has " + handValue + ".")
    } else if (handValue > dealerValue && handValue < 22) {
        console.log("Player wins with " + handValue + "! Dealer had " +              dealerValue + ".")
} else if (dealerValue > 21) {
    console.log("Dealer Busts with " + dealerValue + "! Player has " + handValue + ".")
} else if (dealerValue > handValue && dealerValue < 22) {
    console.log("Dealer wins with " + dealerValue + "! Player had " +   handValue + ".")
}



// Do you hit once? Twice? Or not? Insert your line of code below

// ————————-

Any recommendations for a more efficient way to write this game?

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to Code Review! Nice first question! \$\endgroup\$
    – syb0rg
    May 19, 2016 at 16:33
  • \$\begingroup\$ Could you write out or link to the blackjack rules you're following? For instance, is an ace 1 and 11? \$\endgroup\$ May 19, 2016 at 19:34
  • \$\begingroup\$ Are you running your code against test cases? Do you need to use console.log? \$\endgroup\$ May 24, 2016 at 5:26

1 Answer 1

1
\$\begingroup\$

Better user experience

JavaScript is primarily for web browsers with some exceptions (like node.js). Unless your using node, you won't be able to get user input using the console. Instead of using console.log("New Hand: " + handValue) use:

alert("New Hand: " + handValue);

and to get user input you can use:

var userResponse = prompt("Dealer hits, do you HIT or CALL?");

Check out this JSFiddle to see alert and prompt in action.

You could create a much more interactive user experience using HTML, but since you're quite new to JavaScript, alert and prompt should be fine for now.

Abstracting duplicate code - Create a function to get cards

Currently, you use a randomInt function to hit the dealer and user with a new card. A random int from 1 to 11 sort of works, but it's statistically inaccurate with a deck of cards. As you get better and better at JavaScript you may eventually refactor want to edit your code to more closely models a deck of cards:

// Here is some code that more closely models a deck of cards
var cards = [];
for (var i = 1; i < 11; i++) { // for cards 1-10
  cards = cards.concat([i, i, i, i])
}
cards = cards.concat((new Array(12)).fill(10));

function drawCard() {
  return cards.splice(randInt(0, cards.length), 1);
}

The only problem is that your code is not prepared for such a refactor. You'll need to change all your calls to randInt that are intended to return cards to the new function. To prepare for this refactor, you can abstract the way you get cards into a function:

function drawCard() {
  return randInt(1, 11); // for now
}

// here are your first two cards
handValue += drawCard();
handValue += drawCard();

// here are the Dealers cards
dealerValue += drawCard();
dealerValue += drawCard();

Now any changes to your drawCard function will be changed throughout all your code.

Keeping track of cards given to dealer and user

You could keep track of the cards dealt to players by using arrays. Use one array for each player:

var userCards = [];
var dealerCards = [];

function hit(array) {
  array.push(drawCard());
}

function printHand(message, cards) {
  alert(message + "\n" + cards.join(", ");
}

//usage
hit(userCards);
hit(userCards);
hit(dealerCards);
hit(dealerCards);

printHand("You have:", userCards);
printHand("Dealer has:", dealerCards);

To get the sum of a hand, you can use a for loop:

function getTotal(cards) {
   var sum = 0;

  for (var i = 0; i < cards.length; i++) {
    sum += cards[i];
  }

  return sum;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.