Building a Blackjack Game Using HTML, CSS, and JavaScript: A Step-by-Step Guide

By akohad Apr4,2024

[ad_1]

· Introduction
· Project Overview
· Features of the Blackjack Game
· Prerequisites
· Code Structure
Step 1. HTML Structure:
Step 2. CSS Styling:
Step 3. JavaScript Logic:
· Testing and Debugging
· Lessons Learned
· Deployment
· Future Improvements
· Conclusion

In this project guide, I’ll be sharing the process of building a blackjack game using HTML, CSS, and JavaScript. Blackjack, also known as 21, is a popular card game played in casinos around the world. I chose to build this game to improve my skills in front-end development since the best way to learn JavaScript is to build projects and also create lots of fun, interactive projects.

This blackjack game allows players to play against the computer, also known as the dealer. The objective is to get values less than 21 to continue drawing new cards and a hand value of 21 to get a blackjack, and exceeding 21 means you are out of the game.

The game features a simple user interface where players can place bets, hit a new card to receive another card, stand to end their turn, and see the outcome of the game.

In this project, you are going to develop a Blackjack game that will have the following features:

  • Responsive Design: The app is designed to be responsive, ensuring that it looks good and functions well on various devices and screen sizes.
  • User-friendly interface with clear instructions
  • Betting system to simulate real casino gameplay
  • Dynamic card dealing and animation effects
  • Logic for dealer’s moves based on simple AI

To build this game, you’ll need a basic understanding of HTML, CSS, and JavaScript. You should be familiar with HTML for structuring the game, CSS for styling it, and JavaScript for implementing the game logic.

A text editor or IDE (e.g., Visual Studio Code) is required for writing code, and a web browser is needed for testing. Optional prerequisites include game design concepts and a GitHub account for hosting the game.

Create a new folder for your project, name the folder as you wish, and inside it, create three files named index.html, style.css, and script.js. These files will serve as the foundation for your project. Now open the folder in a text editor or IDE (e.g., Visual Studio Code) and follow the steps below:

Step 1. HTML Structure:

Open theindex.html file and paste the following HTML code for the Blackjack game:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BlackJack Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>BlackJack</h1>

<p id="message-el">Want to play a round?</p>

<p id="cards-el">Cards:</p>

<p id="sum-el">Sum:</p>

<button id="start">Start Game</button>

<button id="new">New Card</button>

<p id="player-el"></p>

<script src="./main.js"></script>
</body>
</html>

The HTML code above sets up a basic structure for the Blackjack game, including headers, messages, buttons for starting the game and drawing new cards, and placeholders for displaying cards and the current sum. The document includes a link to an external CSS file for styling and a script tag linking to a JavaScript file for functionality.

Step 2. CSS Styling:

Open thestyle.css file and paste the following CSS code to style the Blackjack game:

@import url('https://fonts.googleapis.com/css2?family=Acme&family=Carter+One&family=Cookie&family=Island+Moments&family=PT+Serif+Caption&family=Playfair+Display+SC:wght@400;700;900&family=Red+Hat+Display:wght@700;900&family=Roboto+Mono&display=swap');

/* UNIVERSAL BODY STYLING */
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}

/* BODY STYLING */
body{
margin-top: 15px;
font-family: 'Roboto Mono', monospace;
text-align: center;
color: white;
background-color: rgb(5, 51, 5);
}

/* BODY H1 STYLING */
h1{
color: goldenrod;
font-size: 50px;
letter-spacing: 2px;
text-decoration: underline;
margin-bottom: 20px;
cursor: pointer;
}

/* DISPLAY MESSAGE STYLING */
#message-el{
font-style: italic;
font-size: 30px;
margin-bottom: 20px;
}

/* PARAGRAPH MESSAGE STYLING */
p{
font-size: 30px;
margin-bottom: 20px;
}

/* BUTTONS STYLING */
button{
padding: 10px;
border: none;
color: rgb(5, 51, 5);
font-weight: bold;
width: 200px;
font-size: 25px;
border-radius: 3px;
text-transform: uppercase;
background-color: goldenrod;
text-align: center;
margin: auto;
display: flex;
justify-content: center;
margin-bottom: 6px;
margin-top: 6px;
font-family: 'Roboto Mono', monospace;
}

button:hover{
transition: 0.3s ease-in-out;
background-color: #b18005;
}

/* PLAYER MESSAGE STYLING */
#player-el{
margin-top: 20px;
font-weight: bold;
}

/* MEDIA QUERY STYLING STARTS HERE */
@media screen and (max-width: 300px) {
body{
margin-top: 30px;
}

h1{
font-size: 40px;
letter-spacing: 2px;
text-decoration: underline;
margin-bottom: 20px;
}

#message-el{
font-size: 16px;
}

p{
font-size: 17px;
}

button{
padding: 5px;
width: 120px;
font-size: 20px;
}

#player-el{
font-size: 15px;
}
}

The CSS code above styles the Blackjack game, importing Google Fonts and setting up a consistent design. It includes styles for the body, headings, messages, paragraphs, buttons, and player information. Media queries are used to adjust styles for smaller screens.

Step 3. JavaScript Logic:

Open thescript.js file and add functionality to the Blackjack game using the following JavaScript code:

let cards = [];

let sum = 0;

let hasBlackjack = false;

let isAlive = false;

let message = "";

let messageEl = document.getElementById("message-el");

let sumEl = document.getElementById("sum-el");

let cardsEl = document.getElementById("cards-el");

let startEl = document.getElementById("start");

let newEl = document.getElementById("new");

let playerName = "Player";

let playerChip = Math.floor(Math.random() * 51);

let playerEl = document.getElementById("player-el");

playerEl.textContent = `${playerName}: $${playerChip}`;

function getRandomCard() {
let randomNumbers = Math.floor(Math.random() * 13) + 1;
if (randomNumbers > 10) {
return 10;
} else if (randomNumbers === 1){
return 11;
} else{
return randomNumbers;
}
}

startEl.addEventListener('click', () => {
isAlive = true;
let firstCard = getRandomCard();
let secondCard = getRandomCard();
cards = [firstCard, secondCard];
sum = firstCard + secondCard;
renderGame();
document.querySelector("#start").style.display = "none";
})

const resetGame = () => {
cards = [];
sum = 0;
hasBlackjack = false;
isAlive = false;
message = "";
renderGame();
document.querySelector("#start").style.display = "flex";
};

const renderGame = () => {
cardsEl.textContent = `Cards: `;
for (let i = 0; i < cards.length; i++) {
cardsEl.textContent += `${cards[i]} `;
if (i < cards.length - 1) {
cardsEl.textContent += '+ ';
}
}
sumEl.textContent = `Sum: ${sum}`;
if (sum < 21) {
message = "Do you want to draw a new card?";
isAlive = true;
} else if (sum === 21) {
message = "Whoo! You've got BlackJack!";
hasBlackjack = true;
isAlive = true;
setTimeout(() => {
if (confirm('Play Again?')) {
resetGame();
}
}, 1000);
} else {
message = "You're out of the Game!";
isAlive = false;
setTimeout(() => {
if (confirm('Play Again?')) {
resetGame();
}
}, 1000);
}
messageEl.textContent = message;
};

newEl.addEventListener('click', () => {
if(isAlive === true && hasBlackjack === false) {
let card = getRandomCard();
sum += card;
cards.push(card);
renderGame();
}
});

The JavaScript code above defines the Blackjack game with the functionality to start a game, draw new cards, and check for Blackjack or bust. It keeps track of the player’s sum, cards, and status. The game includes a player name and random starting chips. It updates the DOM to display game information and allows the player to reset the game.

To test the application in your web browser, you can follow these steps:

  1. Open the HTML File: Make sure you have saved all your HTML, CSS, and JavaScript files in the same folder as stated earlier. Then, open the HTML file in your web browser by double-clicking on it. This will open the file in your default web browser.
  2. Inspect Element: Once the app is loaded in the browser, right-click on the page and select “Inspect” or press “Ctrl+Shift+I” to open the developer tools. This will allow you to see any errors in the console and inspect elements on the page.
  3. Test Functionality: Interact with your app to test its functionality. This will help you identify any bugs or issues in your code.
  4. Debugging: If you encounter any errors or issues, use the console in the developer tools to debug your JavaScript code. Look for error messages and line numbers to pinpoint where the issue is occurring.
  5. Make Changes: If you need to make changes to your code, go back to your code editor, make the necessary adjustments, save the file, and then refresh the browser to see the changes reflected in your app.

This project taught me the importance of planning and designing the game logic before diving into coding. I also improved my understanding of CSS stylings, JavaScript events, and DOM manipulation, which are crucial for creating interactive web applications.

The Blackjack game project is hosted on GitHub Pages and can be played online by visiting the following link:

Play the Game: https://wasiu-akindoyin.github.io/Black-Jack-Game-Application/

You can access the GitHub repository here to view or contribute to the source code.

In the future, I plan to add more features, such as:

  • Support for multiple players
  • Enhanced graphics and animations
  • Integration with a backend server to store player scores and game history

This Blackjack game is a practical example of game development concepts using HTML, CSS, and JavaScript to improve my understanding of front-end development. I encourage you to try out the game and explore the code to see how it works.

[ad_2]

Source link

By akohad

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *