This week in class we worked through creating a JavaScript Blackjack game.
Given starter code, our goal was to create logic that followed the basic rules of the game Blackjack:
- Player or Dealer wins at 21 or whomever is closer without going over 21.
- Dealer stands after 17.
- An Ace (11) can also be worth 1.
- Cards aren’t duplicated unless multiple decks are used.
I set some stretch goals for myself to disable buttons that weren’t needed, such as disabling Hit and Stand until Deal was clicked, disabling Deal after one click, and disabling Hit after Stand was clicked.
I also wanted to list the total, show a “You Won/Lost” message, and flip the Dealer’s cards over at the end of the game.
I started out feeling comfortable dropping into someone else’s code and began just console logging the object to see what was being produced. From there I chose a simple shuffle algorithm to shuffle the created deck and and moved on to creating a function that would create and append the card element, making one for the Player and one for the Dealer, deleting any dealt cards from the deck after they were appended.
Moving on, I created the logic for the three existing buttons, learning how to disable and re-enable them, and then added in another button right below them to refresh the page and start a new game.
From there I worked on the logic that was run by clicking the buttons. On Deal I would call both element creation functions twice. On Hit, I would call both functions once and on Stand I would call only the Dealer’s function.
Additionally, because I wanted to turn off certain buttons in certain card total situations and needed to add in logic for if the Dealer reached 17, I also needed to create a counting function to update the Player and Dealer totals after each click.
My counting function tracked the current Player/Dealer total by reducing the two global arrays that each held how much each card in their hand was worth and from there I created four if/else sections to handle the different paths. One handled anyone at 21, one recursively handled going over 21 but having an ace, one handled if either the Player or Dealer went bust, and the last one handled if the Dealer hit 17 and the Player hit Stand.
Consequently, each resulting section would update the inner text to include the final Player total and either a win or lost statement. They also disabled the buttons that were not needed in each situation and once the game was over, all the Dealer’s cards were flipped over and their total was revealed.
This was done through a suggestion from our cohort teacher, letting the CSS class content style supersede any src set to the element until that class's style was removed, revealing its underlying src.
Overall, I had fun designing the logic for this game and working through accounting for each game path possibility.
If you'd like to play it:
https://meg-div.github.io/blackjack/
Here's the code:
https://github.com/Meg-Div/blackjack
Top comments (0)