November 6, 2024 (4mo ago)
How to Play:
- Objective: Get as close to 21 as possible without going over, beating the dealer’s total.
- Commands: After pasting the code, you’ll be prompted to type either
hit
(to draw another card) or stand
(to hold your current total).
- Outcome: The dealer will automatically draw cards after you stand, and the winner will be determined.
Instructions:
- Open your browser's developer tools (right-click → Inspect or press
F12
).
- Go to the "Console" tab.
- Copy and paste the following code to start a blackjack game!
(function() {
function getCard() {
const cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11];
return cards[Math.floor(Math.random() * cards.length)];
}
function handTotal(hand) {
let total = hand.reduce((a, b) => a + b, 0);
hand.filter(card => card === 11).forEach(() => {
if (total > 21) total -= 10;
});
return total;
}
function playBlackjack() {
let playerHand = [getCard(), getCard()];
let dealerHand = [getCard(), getCard()];
function showHands() {
console.log(`Your hand: ${playerHand.join(", ")} (Total: ${handTotal(playerHand)})`);
console.log(`Dealer's hand: ${dealerHand[0]}, ?`);
}
showHands();
while (true) {
const action = prompt("Type 'hit' to draw another card or 'stand' to hold your hand:");
if (action.toLowerCase() === 'hit') {
playerHand.push(getCard());
console.clear();
showHands();
if (handTotal(playerHand) > 21) {
console.log("Bust! You went over 21. Dealer wins!");
return;
}
} else if (action.toLowerCase() === 'stand') {
break;
} else {
console.log("Invalid input. Please type 'hit' or 'stand'.");
}
}
while (handTotal(dealerHand) < 17) {
dealerHand.push(getCard());
}
console.clear();
console.log(`Your final hand: ${playerHand.join(", ")} (Total: ${handTotal(playerHand)})`);
console.log(`Dealer's final hand: ${dealerHand.join(", ")} (Total: ${handTotal(dealerHand)})`);
const playerTotal = handTotal(playerHand);
const dealerTotal = handTotal(dealerHand);
if (dealerTotal > 21 || playerTotal > dealerTotal) {
console.log("Congratulations! You win!");
} else if (playerTotal === dealerTotal) {
console.log("It's a tie!");
} else {
console.log("Dealer wins!");
}
}
playBlackjack();
})();