JSFiddle - React, Tailwind, and code Playground
(Pure JS) Text-based game of blackjack
by Don Schaefer
HTML
<h1>Blackjack Results</h1>
<p id="pResult"></p>
<div id="divUser">
<h2>Your Hand:</h2>
<p id="pUserScore"></p>
<ul id="ulUserHand"></ul>
</div>
<div id="divDealer">
<h2>Dealer's Hand:</h2>
<p id="pDealerScore"></p>
<ul id="ulDealerHand"></ul>
</div>
CSS
h1, h2 {
margin: 0;
}
#divUser, #divDealer {
width: 45%;
float: left;
border-right: 1px solid #ccc;
padding: 10px;
}
ul {
margin-left: 25px;
padding-left: 0;
}
#pUserScore, #pDealerScore {
font-weight: bold;
}
JavaScript
var pResult = document.getElementById('pResult');
var ulUserHand = document.getElementById('ulUserHand');
var pUserScore = document.getElementById('pUserScore');
var ulDealerHand = document.getElementById('ulDealerHand');
var pDealerScore = document.getElementById('pDealerScore');
var acesInHand = 0;
// Card Constructor
function card(suitValue, numValue) {
var suit = suitValue;
var number = numValue;
var aceValue = '1 or 11';
this.getNumber = function () {
return number;
};
this.getSuit = function () {
return suit;
};
this.getValue = function () {
switch (number) {
case ("Ace"):
return 11;
case ("King"):
return 10;
case ("Queen"):
return 10;
case ("Jack"):
return 10;
default:
return number;
}
};
this.getStats = function () {
if(this.getValue() != 11){
return '<li>' + this.getNumber() + ' of ' + this.getSuit() + ' | Value: ' + this.getValue() + '</li>';
}else{
return '<li>' + this.getNumber() + ' of ' + this.getSuit() + ' | Value: 1 or 11</li>';
}
};
}
//create arrays to hold possible suit/rank values
var suits = ["Hearts", "Diamonds", "Clubs", "Spades"];
var ranks = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"];
var deck = [];
//create deck array based on suits & rank arrays
function newDeck() {
deck.splice(0, deck.length);
for (var s = 0; s < suits.length; s++) {
for (r = 0; r < ranks.length; r++) {
deck.push(new card(suits[s], ranks[r]));
}
}
}
newDeck();
function deal() {
randNum1 = Math.floor(Math.random() * 3);
randNum2 = Math.floor(Math.random() * 12);
if (randNum2 === 0) {
acesInHand++;
}
var cardID = randNum2 + (randNum1 * 13);
//removing the card from the "deck" array & returning it - note that...