Blackjack program in javascript

  • Context: Comp Sci 
  • Thread starter Thread starter shivajikobardan
  • Start date Start date
  • Tags Tags
    Javascript
Click For Summary

Discussion Overview

The discussion revolves around a JavaScript program designed to calculate the score of a Blackjack hand based on user input for card values. Participants explore the correctness of the code, the handling of specific card values, and the implementation of testing methodologies.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • Some participants point out that face cards (J, Q, K) should score ten each, rather than eleven, twelve, or thirteen as coded.
  • Concerns are raised about the algorithm's handling of multiple aces, suggesting it may not function correctly in scenarios like "T A A".
  • A suggestion is made to separate the calculation logic from input handling to facilitate unit testing, emphasizing the importance of this practice in programming.
  • Participants discuss the need for manual testing and regression testing to ensure code functionality after changes.
  • One participant describes the logic of the code, noting that it correctly counts aces but may not display whether the hand has busted.
  • There is a mention of the potential for the program to handle more than five cards, although the current implementation restricts the number of cards to between two and five.

Areas of Agreement / Disagreement

Participants express disagreement regarding the scoring of face cards and the handling of aces. There is no consensus on the correctness of the code, as multiple viewpoints on its functionality and potential issues are presented.

Contextual Notes

Limitations include the program's current inability to handle more than five cards and the need for further testing to confirm its accuracy. The discussion also highlights the importance of separating concerns in programming for better maintainability and testing.

Who May Find This Useful

Beginner programmers interested in learning about Blackjack game logic, JavaScript coding practices, and unit testing methodologies may find this discussion beneficial.

shivajikobardan
Messages
637
Reaction score
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
I believe the face cards (j,q,k) are suppose to score ten each. Not 11, 12, 13.
 
  • Like
Likes   Reactions: scottdave, Mark44, DrClaude and 2 others
Your algorithm may not work properly when there are more than one ace, for instance "T A A".
 
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.
 
  • Love
Likes   Reactions: Tom.G
pbuk said:
@.Scott @DrClaude net vs. fish: serial hungry man here.
Beginner programmers need mentorship. Apparently, PF is what he has.
 
  • Like
Likes   Reactions: shivajikobardan
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?
 
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   Reactions: berkeman
.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   Reactions: .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".
 

Similar threads

  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K