Blackjack program in javascript

  • Comp Sci
  • Thread starter shivajikobardan
  • Start date
  • Tags
    Javascript
In summary: The best way to find this out is to test it. Real programmers use a unit test framework (for JavaScript we have mocha, Jest or AVA) but for now I would use something like this:function runTests(subject, tests) { for (const [description, input, expected] in tests) { const actual = subject(input); if (actual === expected) { console.log(description, 'passed'); continue; } console.log(description, 'failed', { expected, actual }); }}
  • #1
shivajikobardan
674
54
Homework Statement
Blackjack program in javascript
Relevant Equations
Blackjack program in javascript
1687365328398.png


JavaScript:
let card_value = 0;
let count_of_a = 0;
let number_of_cards = Number(prompt("Enter the number of cards."));
if (number_of_cards >= 2 && number_of_cards <= 5) {

  let cards = [];
  for (let i = 0; i < number_of_cards; i++) {
    cards[i] = prompt("Enter the value of card ");
  }
  var dict = {

    "2": 2,
    "3": 3,
    "4": 4,
    "5": 5,
    "6": 6,
    "7": 7,
    "8": 8,
    "9": 9,
    "t": 10,
    "j": 11,
    "q": 12,
    "k": 13
  };

  for (let j of cards) {
    if (j == "a") {
      count_of_a++;
      continue;
    }
    else {
      card_value += dict[j];
    }
  }
  for (let k = 0; k < count_of_a; k++) {
    dict["a"] = (card_value + 11 > 21) ? 1 : 11,
      card_value += dict["a"];
  }
  console.log(card_value);
}
else {
  console.log("Program ends here. Please enter again.");
}
Is my code correct?
 
Physics news on Phys.org
  • #2
I believe the face cards (j,q,k) are suppose to score ten each. Not 11, 12, 13.
 
  • Like
Likes scottdave, Mark44, DrClaude and 2 others
  • #3
Your algorithm may not work properly when there are more than one ace, for instance "T A A".
 
  • #4
shivajikobardan said:
Is my code correct?
The best way to find this out is to test it. Real programmers use a unit test framework (for JavaScript we have mocha, Jest or AVA) but for now I would use something like this:
JavaScript:
function runTests(subject, tests) {
  for (const [description, input, expected] in tests) {
    const actual = subject(input);
    if (actual === expected) {
      console.log(description, 'passed');
      continue;
    }
    console.log(description, 'failed', { expected, actual });
  }
}

runTests(calculateScore, [
  ['It should calculate Ace high', [5, 5, 'a'], 21],
  ['It should calculate Ace low', [5, 6, 'a'], 12],
  ...
]);
First you need to separate the calculation part from the parts accepting input and reporting results: this is called separation of concerns and is a vital concept in any programming language.
 
  • #5
  • Love
Likes Tom.G
  • #6
pbuk said:
@.Scott @DrClaude net vs. fish: serial hungry man here.
Beginner programmers need mentorship. Apparently, PF is what he has.
 
  • Like
Likes shivajikobardan
  • #7
pbuk said:
First you need to separate the calculation part from the parts accepting input and reporting results: this is called separation of concerns and is a vital concept in any programming language.
Hey, so my code is working right? except the fact j,k,q are 10? How do you separate calculation parts from accepting input part?
 
  • #8
shivajikobardan said:
How do you separate calculation parts from accepting input part?
First let me make sure you understand why you would separate it - which is to assist in unit testing. If you put lines 10 to 38 of your JavaScript code into a function (I'll call it Score21), then you can write test code that passes is test cases and checks the result for accuracy (a @pbuk suggested). Lines 10 to 38 are the meat of your code - where subtle errors are most likely. So if you can systematically run a dozen well-chosen test cases against it, it can provide your and others with confidence-inspiring evidence that the code is doing what you want.

Of course, that still leaves your other 15 lines of code untested. Testing those require feeding the "prompt" function and checking the output of the console.log function. There are techniques for doing that automatically, but let's leave it as just a manual test procedure - run the program, enter test values, read and verify the result.

There is a part 2 to this. Two months later, the requirements change a bit. Say you want to support '0' and an alternate to 't' for specifying the "ten" card. So you make the appropriate changes, and then rerun the original test for function Score21. That would be a "regression test" and it tells you whether you have broken anything.

Then you would update that regression test to include another 1 or 2 test cases for the new "0" feature and test it again.

Then repeat the manual testing.
Finally put together the design/test-report/code merge request package for peer review - but that's a whole new topic.
 
  • Like
Likes berkeman
  • #9
.Scott said:
I believe the face cards (j,q,k) are suppose to score ten each. Not 11, 12, 13.
And this is stated in the problem description.
 
  • Like
Likes .Scott
  • #10
As I understand your code, you will choose the total number of cards, between 2 to 5 cards, without predetermining the value of each card, and then you will iterate through each of your chosen total number of cards and assign each card its value in an array (cards[]).

You will then iterate through your cards[] array and add the total of each card to the card_value variable (card_value += dict[j];), but aces ("a") are not yet in the dictionary object, so if your code encounters an ace ("a"), it will simply count the number of aces without yet adding any number to the card-value variable:
if (j == "a") {
count_of_a++;
* * *
}

After counting the number of aces, your program will ask that number of times if the card_value total of all the cards plus 11 is less than 21. If less than 21, your program will assign the value of 11 to "a" in your dictionary object and add that value to the card_value total of all the cards, but if the total card_value plus 11 is equal to or greater than 21, then your program will assign the value of 1 to your dictionary object and add that value to the card_value total of all the cards. Thus, the value of "a" in your dictionary object can change.

Barring any syntax issues, it is a clever piece of logic.

Finally, your program writes your hand total to console.log, though it does not display whether the hand busted as you originally intended.

I put your program into the Code IDE, and all the brackets seem to be correctly nested. I would put the program as javascript inside an html page with some different coding to display everything to see if it works, but I have not done so.

Of course, you know that an actual blackjack hand can have more than five cards without busting, but I assume that this was a test for correctly assigning the value of 11 or 1 to aces.
 
  • #11
RayDonaldPratt said:
Barring any syntax issues, it is a clever piece of logic.
Except it doesn't work for e.g.
DrClaude said:
Your algorithm may not work properly when there are more than one ace, for instance "T A A".
 

FAQ: Blackjack program in javascript

```html

How do I start creating a Blackjack program in JavaScript?

To start creating a Blackjack program in JavaScript, you need a basic understanding of HTML, CSS, and JavaScript. Begin by setting up your HTML structure and linking your JavaScript file. Define the rules and logic of Blackjack, such as dealing cards, calculating scores, and determining the winner. Use JavaScript to handle game mechanics and user interactions.

How do I represent a deck of cards in JavaScript?

You can represent a deck of cards in JavaScript using an array of objects. Each object can have properties such as suit and value. For example, a card object might look like this: {suit: 'Hearts', value: 'A'}. You can then create a function to generate a full deck of 52 cards by iterating over all possible suits and values.

How do I shuffle the deck of cards in my Blackjack game?

To shuffle the deck of cards, you can use the Fisher-Yates shuffle algorithm. This algorithm iterates through the array and swaps each element with a random element that comes after it. Here is a simple implementation in JavaScript:

function shuffle(deck) {  for (let i = deck.length - 1; i > 0; i--) {    const j = Math.floor(Math.random() * (i + 1));    [deck[i], deck[j]] = [deck[j], deck[i]];  }  return deck;}

How do I handle player actions like 'Hit' and 'Stand' in my Blackjack game?

To handle player actions like 'Hit' and 'Stand', you can create functions in JavaScript that modify the game state based on the player's choices. For example, a 'Hit' function can add a new card to the player's hand and check if the player has busted. A 'Stand' function can switch the turn to the dealer and handle the dealer's actions according to the game rules.

How do I calculate the score of a hand in Blackjack?

To calculate the score of a hand in Blackjack, you need to sum the values of the cards in the hand. Number cards are worth their face value, face cards (Jack, Queen, King) are worth 10, and Aces can be worth either 1 or 11, depending on which value is more beneficial without causing a bust. You can create a function to iterate through the hand, calculate the total score, and adjust for Aces as needed.

```

Similar threads

Replies
8
Views
1K
Replies
4
Views
1K
Replies
3
Views
1K
Replies
22
Views
1K
Replies
21
Views
2K
Replies
9
Views
1K
Replies
5
Views
2K
Replies
7
Views
2K
Back
Top