Functionalities of Frontend

  • The code imports React, Axios (for HTTP requests), and a CSS file for styling.
  • It declares a functional React component named Game, with state variables for managing game state and displaying the winner message.
  • The useEffect hook fetches the initial game state from the backend ( <a href=”http://localhost:5000/game/start” target=”_new” > http://localhost:5000/game/start </a > ) when the component mounts.
  • handleHit: Sends an Axios request to the backend to implement player hitting logic.
  • handleStand: Sends an Axios request to the backend to implement player standing logic.
  • startNewGame: Sends an Axios request to start a new game and clears the winner message.Displays the winner message and starts a new game after a 3-second delay using setTimeout.Uses setTimeout to automatically trigger a new game.Displays a loading message while fetching the game state from the backend.

Javascript




// blackjack-client/src/Game.js
 
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './App.css';
 
const Game = () => {
    const [gameState, setGameState] = useState(null);
    const [winnerMessage, setWinnerMessage] = useState('');
 
    useEffect(() => {
        // Fetch initial game state when the component mounts
        axios.post('http://localhost:5000/game/start')
            .then(response => setGameState(response.data))
            .catch(error =>
                console.error('Error starting a new game:', error));
    }, []);
 
    const handleHit = () => {
        // Implement logic for the player to hit
        axios.post('http://localhost:5000/game/hit',
            { gameId: gameState._id })
            .then(response => {
                setGameState(response.data);
                checkWinner(response.data.winner);
            })
            .catch(error => console.error('Error hitting:', error));
    };
 
    const handleStand = () => {
        // Implement logic for the player to stand
        axios.post('http://localhost:5000/game/stand',
            { gameId: gameState._id })
            .then(response => {
                setGameState(response.data);
                checkWinner(response.data.winner);
            })
            .catch(error =>
                console.error('Error standing:', error));
    };
 
    const startNewGame = () => {
        // Implement logic to start a new game
        setWinnerMessage(''); // Clear the winner message
        axios.post('http://localhost:5000/game/start')
            .then(response => setGameState(response.data))
            .catch(error =>
                console.error('Error starting a new game:', error));
    };
 
    const checkWinner = (winner) => {
        // Display winner message and start a new game
        setWinnerMessage(`Winner: ${winner}`);
        setTimeout(() => {
            startNewGame();
        }, 3000); // Automatically start a new game after 3 seconds
    };
 
    return (
        <div className="kl">
            {gameState ? (
                <>
                    <h1>Blackjack Game</h1>
                    {winnerMessage && <p className="winner-message">
                        {winnerMessage} </p>}
                    <div className="ma">
 
                        <div className="playerside">
                            <h2>Player Hand:</h2>
                            <ul>
                                {gameState.player.hand.map((card, index) => (
                                    <li key={index}>{card.rank}
                                        of {card.suit}</li>
                                ))}
                            </ul>
                            <p>Score: {gameState.player.score}</p>
                        </div>
                        <div className="dealerside">
                            <h2>Dealer Hand:</h2>
                            <ul>
                                {gameState.dealer.hand.map((card, index) => (
                                    <li key={index}>{card.rank}
                                        of {card.suit}</li>
                                ))}
                            </ul>
                            <p>Score: {gameState.dealer.score}</p>
                        </div>
                    </div>
                    <div className="buttons">
                        <button onClick={handleHit}>Hit</button>
                        <button onClick={handleStand}>Stand</button>
                        <button onClick={startNewGame}>
                            Start New Game
                        </button>
                    </div>
                </>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );
};
 
export default Game;


CSS




/* blackjack-client/src/App.css */
 
body {
    background-color: #00203F;
    color: #ADEFD1;
    font-family: sans-serif;
}
 
.App {
    text-align: center;
    padding: 20px;
}
 
 
ul {
    list-style-type: none;
    padding: 0;
}
 
button {
    background-color: #ADEFD1;
    color: #00203F;
    border: none;
    padding: 10px 20px;
    margin: 5px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}
 
button:hover {
    background-color: #00203F;
    color: #ADEFD1;
}
 
.winner-message {
    color: #FF5555;
    font-size: 30px;
    font-weight: bolder;
    margin-top: 20px;
    animation: fadeIn 1s ease;
}
 
@keyframes fadeIn {
    from {
        opacity: 0;
    }
 
    to {
        opacity: 1;
    }
}
 
.ma {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
}
 
h2,
p {
    color: #00203F;
}
 
.playerside {
    padding: 2%;
    background-color: #ADEFD1;
    color: #00203F;
    width: fit-content;
    margin: 2%;
    border-radius: 35px;
}
 
.dealerside {
    width: fit-content;
    margin: 2%;
    border-radius: 35px;
    padding: 2%;
    background-color: #ADEFD1;
    color: #00203F;
}


Steps to Run the frontend:

1. Navigate to blackjack-frontend root directory.

cd blackjack-frontend

2. Run the following command.

npm start

Output:



Blackjack Game using MERN Stack

In this tutorial, we’ll embark on a journey to create a fully functional Blackjack game using React for the frontend and Node for the backend. This engaging and interactive project will allow you to explore the realms of web development while learning how to implement key features of a classic card game.

Preview of Final Output: Let’s have a look at what our final project will look like:

Similar Reads

Prerequisites:

NodeJS ReactJS MongoDB Express MERN Stack...

Approach to create Blackjack Game:

Backend (Node): Set up a NodeJS server using Express. Create a MongoDB database to store game data. Implement routes for starting a new game, hitting, and standing. Define logic to determine winners and calculate scores. Frontend (React): Develop a responsive UI for the Blackjack game. Connect the frontend to the backend using Axios for API calls. Implement functionalities for hitting, standing, and starting a new game. Display game state, player and dealer hands, and winner messages....

Functionalities of Backend:

Importing modules such as Express, Mongoose, cors, and body-parser. Creating an Express app, setting the server port. Middleware is used to Enabling CORS and JSON data parsing. Connecting to a local MongoDB database. Defining Mongoose schemas and models for Card, Player, and Game. Creating a function to generate a shuffled deck. Endpoint (/game/start): Starts a new game, initializes player and dealer cards, calculates scores, and saves the game state. Endpoints (/game/hit and /game/stand): Handle player hits and stands, update game state, and determine the winner. Functions (calculateScore and determineWinner): Calculate hand scores and determine game winner. Starting the server and listening on the specified port (either from the environment variable or defaulting to 5000)....

Steps To Create The Backend:

Step 1: Create a new NodeJS project....

Project Structure(Backend):

...

Steps To Create The Frontend:

...

Project Structure(Frontend):

Step 1: Set up a new React app using create-react-app....

Functionalities of Frontend:

...