CSS: Styling the Game
The CSS styles enhance the visual appeal and responsiveness of the game:

* {        box-sizing: border-box;        margin: 0;        padding: 0;}body {        font-family: Arial, sans-serif;        line-height: 1.6;        text-align: center;        justify-content: center;        display: flex;        color: #333;        background: linear-gradient(to bottom, #a8edea, #fed6e3);        align-items: center;        margin: 0;        height: 100vh;        /* background-color: #f9f9f9; */}#game-container {        display: flex;        flex-direction: column;        width: 80%;        margin: 50px auto;        padding: 20px;        border: 1px solid #ccc;        border-radius: 10px;        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);        /* justify-content: center; */        align-items: center;        background: rgba(255, 255, 255, 0.8);        text-align: center;}h1 {        font-family: \\\"Pacifico\\\", cursive;        color: #ff6f61;}#word-container {        display: flex;        align-items: center;        justify-content: center;        font-size: 24px;        font-weight: bold;        margin-bottom: 20px;}.logo {        height: 80px;        width: 83px;}.letter-btn {        margin: 10px;        padding: 10px 20px;        border: none;        border-radius: 8px;        color: #fff;        background: #ff6f61;        cursor: pointer;        transition: background 0.3s ease;}.letter-btn:hover {        background-color: #ff402e;}.letter-btn.disabled {        background-color: #ccc;        cursor: not-allowed;}#message {        font-size: 18px;        font-weight: bold;        color: #666;        margin-bottom: 20px;}#restart-btn {        font-weight: bold;        padding: 10px 20px;        border: none;        border-radius: 10px;        background-color: #ff6f61;        color: #fff;        cursor: pointer;        margin-bottom: 20px;}#restart-btn:hover {        background-color: #ff402e;}#hangman-img {        width: 180px;        height: 180px;        margin: 0 20px;        transition: transform 0.3s ease-in-out;}.hangman-image:hover {        transform: scale(1.05);}#clue {        font-size: 18px;        font-weight: bold;        margin-bottom: 20px;        color: darkblue;}#tries {        position: relative;        left: 30%;        margin: 10px;        /* margin-left: 900px; */        padding: 10px 20px;        border: none;        border-radius: 10px;        background-color: #4fd8d8;        color: #fff;        cursor: pointer;}/* Media Queries *//* Small screens (max-width: 768px) */@media (max-width: 768px) {        #game-container {                display: flex;                flex-direction: column;                width: 90%;                margin: 20px auto;                height: 100vh;                padding: 10px;                align-items: center;        }        #word-container {                font-size: 18px;        }        .letter-btn {                margin: 5px;                padding: 5px 10px;        }        #letters-container {                width: 350px;        }        #message {                font-size: 14px;                font-weight: bold;        }        #restart-btn {                height: 30px;                padding: 5px 10px;        }        #hangman-img {                width: 120px;                height: 120px;        }        #clue {                font-size: 14px;        }        #tries {                /* margin: 5px; */                left: 30%;                padding: 13px 5px 10px 5px;        }}/* Extra small screens (max-width: 480px) */@media (max-width: 480px) {        #game-container {                display: flex;                flex-direction: column;                width: 100%;                height: 100vh;                margin: 10px auto;                padding: 5px;                align-items: center;                background:#ebfcfc;        }        #letters-container {                /* width: 280px; */                flex-wrap: wrap;                margin-bottom: 30px;        }        #word-container {                font-size: 20px;        }        .letter-btn {                height: 30px;                width: 30px;                border-radius: 100%;                margin: 2px;                padding: 2px 5px;        }        #message {                font-weight: bold;                font-size: 30px;                margin: 10px 0 10px 0;        }        #restart-btn {                margin-top: 30px;                height: 40px;                font-size: 20px;                padding: 2px 5px;        }        #hangman-img {                width: 170px;                height: 170px;                margin: 30px 0 0px 0;        }        #clue {                margin-top: 40px;                font-size: 21px;        }        #tries {                left: 9%;                width: 150px;                flex-wrap: wrap;                margin: 20px 0 40px 0;                padding: 15px;                margin-left: 170px;        }}@media (max-width: 320px) {        #game-container {                display: flex;                flex-direction: column;                width: 100%;                height: 100vh;                margin: 10px auto;                padding: 5px;                align-items: center;                background:#ebfcfc;        }        #letters-container {                width: 270px;                flex-wrap: wrap;                margin-bottom: 20px;        }        #word-container {                font-size: 20px;        }        .letter-btn {                margin: 2px;                padding: 2px 5px;        }        #message {                font-weight: bold;                font-size: 15px;        }        #restart-btn {                font-size: medium;                padding: 2px 5px;        }        #hangman-img {                width: 120px;                height: 120px;                margin: 15px 0 0px 0;        }        #clue {                margin-top: 10px;                font-size: 18px;        }        #tries {                left: 20%;                margin: 2px;                padding: 15px 0 0 0;        }}* {        box-sizing: border-box;        margin: 0;        padding: 0;}body {        font-family: Arial, sans-serif;        line-height: 1.6;        text-align: center;        justify-content: center;        display: flex;        color: #333;        background: linear-gradient(to bottom, #a8edea, #fed6e3);        align-items: center;        margin: 0;        height: 100vh;        /* background-color: #f9f9f9; */}#game-container {        display: flex;        flex-direction: column;        width: 80%;        margin: 50px auto;        padding: 20px;        border: 1px solid #ccc;        border-radius: 10px;        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);        /* justify-content: center; */        align-items: center;        background: rgba(255, 255, 255, 0.8);        text-align: center;}h1 {        font-family: \\\"Pacifico\\\", cursive;        color: #ff6f61;}#word-container {        display: flex;        align-items: center;        justify-content: center;        font-size: 24px;        font-weight: bold;        margin-bottom: 20px;}.logo {        height: 80px;        width: 83px;}.letter-btn {        margin: 10px;        padding: 10px 20px;        border: none;        border-radius: 8px;        color: #fff;        background: #ff6f61;        cursor: pointer;        transition: background 0.3s ease;}.letter-btn:hover {        background-color: #ff402e;}.letter-btn.disabled {        background-color: #ccc;        cursor: not-allowed;}#message {        font-size: 18px;        font-weight: bold;        color: #666;        margin-bottom: 20px;}#restart-btn {        font-weight: bold;        padding: 10px 20px;        border: none;        border-radius: 10px;        background-color: #ff6f61;        color: #fff;        cursor: pointer;        margin-bottom: 20px;}#restart-btn:hover {        background-color: #ff402e;}#hangman-img {        width: 180px;        height: 180px;        margin: 0 20px;        transition: transform 0.3s ease-in-out;}.hangman-image:hover {        transform: scale(1.05);}#clue {        font-size: 18px;        font-weight: bold;        margin-bottom: 20px;        color: darkblue;}#tries {        position: relative;        left: 30%;        margin: 10px;        /* margin-left: 900px; */        padding: 10px 20px;        border: none;        border-radius: 10px;        background-color: #4fd8d8;        color: #fff;        cursor: pointer;}/* Media Queries *//* Small screens (max-width: 768px) */@media (max-width: 768px) {        #game-container {                display: flex;                flex-direction: column;                width: 90%;                margin: 20px auto;                height: 100vh;                padding: 10px;                align-items: center;        }        #word-container {                font-size: 18px;        }        .letter-btn {                margin: 5px;                padding: 5px 10px;        }        #letters-container {                width: 350px;        }        #message {                font-size: 14px;                font-weight: bold;        }        #restart-btn {                height: 30px;                padding: 5px 10px;        }        #hangman-img {                width: 120px;                height: 120px;        }        #clue {                font-size: 14px;        }        #tries {                /* margin: 5px; */                left: 30%;                padding: 13px 5px 10px 5px;        }}/* Extra small screens (max-width: 480px) */@media (max-width: 480px) {        #game-container {                display: flex;                flex-direction: column;                width: 100%;                height: 100vh;                margin: 10px auto;                padding: 5px;                align-items: center;                background:#ebfcfc;        }        #letters-container {                /* width: 280px; */                flex-wrap: wrap;                margin-bottom: 30px;        }        #word-container {                font-size: 20px;        }        .letter-btn {                height: 30px;                width: 30px;                border-radius: 100%;                margin: 2px;                padding: 2px 5px;        }        #message {                font-weight: bold;                font-size: 30px;                margin: 10px 0 10px 0;        }        #restart-btn {                margin-top: 30px;                height: 40px;                font-size: 20px;                padding: 2px 5px;        }        #hangman-img {                width: 170px;                height: 170px;                margin: 30px 0 0px 0;        }        #clue {                margin-top: 40px;                font-size: 21px;        }        #tries {                left: 9%;                width: 150px;                flex-wrap: wrap;                margin: 20px 0 40px 0;                padding: 15px;                margin-left: 170px;        }}@media (max-width: 320px) {        #game-container {                display: flex;                flex-direction: column;                width: 100%;                height: 100vh;                margin: 10px auto;                padding: 5px;                align-items: center;                background:#ebfcfc;        }        #letters-container {                width: 270px;                flex-wrap: wrap;                margin-bottom: 20px;        }        #word-container {                font-size: 20px;        }        .letter-btn {                margin: 2px;                padding: 2px 5px;        }        #message {                font-weight: bold;                font-size: 15px;        }        #restart-btn {                font-size: medium;                padding: 2px 5px;        }        #hangman-img {                width: 120px;                height: 120px;                margin: 15px 0 0px 0;        }        #clue {                margin-top: 10px;                font-size: 18px;        }        #tries {                left: 20%;                margin: 2px;                padding: 15px 0 0 0;        }}

JavaScript
was used majorly for the conditionals and interactivity of the game.

const languages = [\\\"javascript\\\", \\\"python\\\", \\\"java\\\", \\\"ruby\\\"];const frameworks = [\\\"react\\\", \\\"angular\\\", \\\"vue\\\", \\\"django\\\", \\\"flask\\\"];const tools = [\\\"git\\\", \\\"webpack\\\", \\\"babel\\\", \\\"eslint\\\", \\\"prettier\\\"];const concept = [\\\"closure\\\", \\\"callback\\\", \\\"promises\\\", \\\"async\\\", \\\"hosting\\\"];const databases = [\\\"mongodb\\\", \\\"sqlite\\\", \\\"mysql\\\"];const allObjects = {languages, frameworks, tools, concept, databases};let chosenWord = \\\"\\\";let guessedLetters = [];let wrongGuesses;const wordContainer = document.getElementById(\\\"word-container\\\");const lettersContainer = document.getElementById(\\\"letters-container\\\");const message = document.getElementById(\\\"message\\\");const restartBtn = document.getElementById(\\\"restart-btn\\\");const hangmanImg = document.getElementById(\\\"hangman-img\\\");const hangmanAud = document.getElementById(\\\"hangman-aud\\\");const trials = document.getElementById(\\\"tries\\\");const clue = document.getElementById(\\\"clue\\\");function init() {        const randomArray =                Object.values(allObjects)[                        Math.floor(Math.random() * Object.keys(allObjects).length)                ];        const randomValue =                randomArray[Math.floor(Math.random() * randomArray.length)];        console.log(randomValue);        const getClue = () => {                for (const [key, value] of Object.entries(allObjects)) {                        if (value.includes(randomValue)) {                                return key;                        }                }        };        clue.textContent = `Clue: \\\"${getClue().toUpperCase()}\\\" in Programming`;        chosenWord = randomValue;        // words[Math.floor(Math.random() * words.length)];        guessedLetters = [];        remainingGuesses = 5;        message.textContent = \\\"\\\";        wordContainer.innerHTML = \\\"_ \\\".repeat(chosenWord.length).trim();        lettersContainer.innerHTML = \\\"\\\";        hangmanImg.src = \\\"hangmanSteady.png\\\";        trials.innerText = \\\"YOU HAVE 5 TRIALS!\\\";        wrongGuesses = 0;        for (let i = 65; i <= 90; i  ) {                const letterBtn = document.createElement(\\\"button\\\");                letterBtn.classList.add(\\\"letter-btn\\\");                letterBtn.textContent = String.fromCharCode(i);                letterBtn.addEventListener(\\\"click\\\", handleGuess);                lettersContainer.appendChild(letterBtn);        }}//after  click this disables all buttons function disableAllButtons() {        const buttons = document.querySelectorAll(\\\".letter-btn\\\");        buttons.forEach((button) => {                button.classList.add(\\\"disabled\\\");                button.disabled = true;        });}restartBtn.addEventListener(\\\"click\\\", init);init();//this handles guesses function handleGuess(event) {        const letter = event.target.innerText.toLowerCase();        event.target.classList.add(\\\"disabled\\\");        event.target.disabled = true;        if (chosenWord.includes(letter)) {                guessedLetters.push(letter);                const displayWord = chosenWord                        .split(\\\"\\\")                        .map((letter) => (guessedLetters.includes(letter) ? letter : \\\"_\\\"))                        .join(\\\" \\\");                wordContainer.textContent = displayWord;        } else {                wrongGuesses  ;                if (wrongGuesses === 1) {                        trials.innerText = \\\"4 trials left\\\";                        hangmanImg.src = \\\"hangman1.png\\\";                        hangmanAud.src = \\\"failed.mp3\\\";                        hangmanAud.play();                } else if (wrongGuesses === 2) {                        hangmanImg.src = \\\"hangman2.png\\\";                        trials.innerText = \\\"3 trials left\\\";                        hangmanAud.src = \\\"failed.mp3\\\";                        hangmanAud.play();                } else if (wrongGuesses === 3) {                        hangmanImg.src = \\\"hangman3.png\\\";                        trials.innerText = \\\"2 trials left\\\";                        hangmanAud.src = \\\"failed.mp3\\\";                        hangmanAud.play();                } else if (wrongGuesses === 4) {                        hangmanImg.src = \\\"hangman4.png\\\";                        trials.innerText = \\\"1 trials left\\\";                        hangmanAud.src = \\\"failed.mp3\\\";                        hangmanAud.play();                }        }        handleGameOver();}const handleGameOver = () => {        if (wrongGuesses === 5) {                message.textContent = `Game Over! ❌ The word was  \\\"${chosenWord}\\\".`;                disableAllButtons();                hangmanImg.src = \\\"hangmanFailed.png\\\";                trials.innerText = \\\"0 TRIAL!\\\";                hangmanAud.src = \\\"gameover.mp3\\\";                hangmanAud.play();                document.querySelector(\\\"#message\\\").style.color = \\\"red\\\";        }        if (chosenWord.split(\\\"\\\").every((letter) => guessedLetters.includes(letter))) {                message.textContent = \\\"Congratulations! You guessed the word!\\\";                hangmanImg.src = \\\"hangmanSuccess.png\\\";                trials.innerText = \\\"Congrats!\\\";                hangmanAud.src = \\\"success.mp3\\\";                hangmanAud.play();                document.querySelector(\\\"#message\\\").style.color = \\\"green\\\";                disableAllButtons();        }};

Code Explanation;
I created an object of arrays. The array names serve as the clue to the word. The game is such that it randomly loops into the objects then gets a single array, for example if after it loops and finally gets the languages array. It then randomly loops over the language array and hides the guess. Hence the player only has a clue of what is to be guessed . So if the guessed word is “python”. The player gets to attempt to guess the word. If after 5 failed attempts of guesses, you failed the game and will have to restart. But if you get the word without 5 failed attempts you get a congratulation message.
The addition of images and audio makes the game intriguing making it much more interactive.

Conclusion
Developing this Hangman game was a rewarding experience that allowed me to apply and enhance my skills in JavaScript. The game’s features, including trial tracking, clues, dynamic images, and feedback messages, create an engaging and interactive experience for players. Deploying the game on Vercel ensures it is accessible and shareable, showcasing the capabilities of modern web development tools and practices.

Future Advancement.
I would be looking forward to adding new characteristics to the game in the future to implement.

Future implementation
The MTnD Hangman game can be used in different niches, only left for me to tailor the objects to your niche, the only things I’ll be needing are keywords that align with your specific niche. The MTnD hangman could be applied in the following;

  1. Educational Hangman: Tailor the game for specific subjects like math, science, or history, where players guess terms related to these topics.
  2. Themed Hangman: Create themes such as movies, books, or famous personalities for each game session.
  3. Multilingual Hangman: Offer versions in different languages to help with language learning.
  4. Custom Word Lists: Allow users to upload or create their own word lists for a personalized experience.
  5. Difficulty Levels: Include options for easy, medium, and hard difficulty levels based on word length or complexity.
  6. Story Mode: Incorporate a storyline or progress system where players unlock new levels or challenges as they succeed.

Each niche could provide a unique twist to the MTnD Hangman game and attract different audiences.
I would be open to suggestions on this project.

","image":"http://www.luping.net/uploads/20240816/172380240566bf23259ef14.jpg","datePublished":"2024-08-16T18:00:05+08:00","dateModified":"2024-08-16T18:00:05+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 JavaScript 建立動態絞刑吏遊戲:技術概述

使用 JavaScript 建立動態絞刑吏遊戲:技術概述

發佈於2024-08-16
瀏覽:528

Creating a Dynamic Hangman Game with JavaScript: A Technical Overview

Introduction
MTnD Hangman game, a classic word-guessing game, serves as an excellent project to practice and showcase various web development skills. In this project, I developed a Hangman game with enhanced features, including tracking the number of trials, providing clues, displaying trial counts, updating images after failed attempts, and displaying a congratulatory message for correct guesses. The game was deployed on Vercel, allowing for easy sharing and access.
This game demo can be assessed here
Features

  1. Number of Trials: The game tracks the number of incorrect guesses a player has made. Each incorrect guess reduces the number of remaining trials, adding to the challenge.
  2. Clues: Players can receive clues to help them guess the word. This feature adds a layer of strategy and assistance, making the game more engaging, enhancing the user experience by offering hints when needed. Visual feedback, including changing images and congratulatory messages, was integrated to make the game more engaging and visually appealing.
  3. Displaying the Number of Trials: The number of trials left is displayed prominently, keeping the player informed and adding to the suspense.
  4. Changing Images After Failed Attempts: For each incorrect guess, the game updates an image, typically depicting the progression of the hangman drawing. This visual feedback enhances the player experience by visually representing the consequences of incorrect guesses. 5.Congratulatory Message for Correct Guesses: When the player successfully guesses the word, a congratulatory message is displayed, providing positive reinforcement and a satisfying conclusion to the game.
  5. Game Logic: The core game logic was implemented in JavaScript functions, handling tasks such as validating guesses, updating the state, and determining win/loss conditions.
  6. Deployment: Once the game was complete and thoroughly tested, it was deployed on Vercel. The deployment process involved pushing the code to a Git repository and connecting it to Vercel, which handled the rest of the deployment seamlessly. 8.Audios were added to indicate wrong guesses which makes the game more intriguing, after 5 failed attempts it also returns at sound. After a successful attempt to get the word you get a sound also for success

Technologies Used

  1. HTML: Structure of the game.
  2. CSS: Styling the game interface.
  3. JavaScript used for web interactivity and conditionals. 4.Vercel: The game is deployed on Vercel, a popular platform for deploying front-end projects.Vercel provides a seamless deployment process and ensures the game is accessible from anywhere.

HTML: Structure of the Game
The HTML structure is straightforward, with a few divs and elements to display the game’s components like empty image tags , heading tags and audio tags to be accessible for toggling different game states.


        
                Hangman

MTnD Hangman

Hangman Image

CSS: Styling the Game
The CSS styles enhance the visual appeal and responsiveness of the game:

* {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
}
body {
        font-family: Arial, sans-serif;
        line-height: 1.6;
        text-align: center;
        justify-content: center;
        display: flex;
        color: #333;
        background: linear-gradient(to bottom, #a8edea, #fed6e3);
        align-items: center;
        margin: 0;
        height: 100vh;
        /* background-color: #f9f9f9; */
}

#game-container {
        display: flex;
        flex-direction: column;
        width: 80%;
        margin: 50px auto;
        padding: 20px;
        border: 1px solid #ccc;
        border-radius: 10px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        /* justify-content: center; */
        align-items: center;
        background: rgba(255, 255, 255, 0.8);
        text-align: center;
}
h1 {
        font-family: "Pacifico", cursive;
        color: #ff6f61;
}
#word-container {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 20px;
}

.logo {
        height: 80px;
        width: 83px;
}
.letter-btn {
        margin: 10px;
        padding: 10px 20px;
        border: none;
        border-radius: 8px;
        color: #fff;
        background: #ff6f61;
        cursor: pointer;
        transition: background 0.3s ease;
}
.letter-btn:hover {
        background-color: #ff402e;
}
.letter-btn.disabled {
        background-color: #ccc;
        cursor: not-allowed;
}

#message {
        font-size: 18px;
        font-weight: bold;
        color: #666;
        margin-bottom: 20px;
}

#restart-btn {
        font-weight: bold;
        padding: 10px 20px;
        border: none;
        border-radius: 10px;
        background-color: #ff6f61;
        color: #fff;
        cursor: pointer;
        margin-bottom: 20px;
}
#restart-btn:hover {
        background-color: #ff402e;
}
#hangman-img {
        width: 180px;
        height: 180px;
        margin: 0 20px;
        transition: transform 0.3s ease-in-out;
}
.hangman-image:hover {
        transform: scale(1.05);
}


#clue {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
        color: darkblue;

}

#tries {
        position: relative;
        left: 30%;
        margin: 10px;

        /* margin-left: 900px; */
        padding: 10px 20px;
        border: none;
        border-radius: 10px;
        background-color: #4fd8d8;
        color: #fff;
        cursor: pointer;
}
/* Media Queries */

/* Small screens (max-width: 768px) */
@media (max-width: 768px) {
        #game-container {
                display: flex;
                flex-direction: column;
                width: 90%;
                margin: 20px auto;
                height: 100vh;
                padding: 10px;
                align-items: center;
        }
        #word-container {
                font-size: 18px;
        }
        .letter-btn {
                margin: 5px;
                padding: 5px 10px;
        }
        #letters-container {
                width: 350px;
        }
        #message {
                font-size: 14px;
                font-weight: bold;
        }
        #restart-btn {
                height: 30px;
                padding: 5px 10px;
        }
        #hangman-img {
                width: 120px;
                height: 120px;
        }
        #clue {
                font-size: 14px;
        }

        #tries {
                /* margin: 5px; */
                left: 30%;
                padding: 13px 5px 10px 5px;
        }
}

/* Extra small screens (max-width: 480px) */
@media (max-width: 480px) {
        #game-container {
                display: flex;
                flex-direction: column;
                width: 100%;
                height: 100vh;
                margin: 10px auto;
                padding: 5px;
                align-items: center;
                background:#ebfcfc;

        }

        #letters-container {
                /* width: 280px; */
                flex-wrap: wrap;
                margin-bottom: 30px;
        }
        #word-container {
                font-size: 20px;

        }
        .letter-btn {
                height: 30px;
                width: 30px;
                border-radius: 100%;
                margin: 2px;
                padding: 2px 5px;
        }
        #message {
                font-weight: bold;
                font-size: 30px;
                margin: 10px 0 10px 0;
        }
        #restart-btn {
                margin-top: 30px;
                height: 40px;
                font-size: 20px;
                padding: 2px 5px;
        }
        #hangman-img {
                width: 170px;
                height: 170px;
                margin: 30px 0 0px 0;
        }
        #clue {
                margin-top: 40px;
                font-size: 21px;
        }

        #tries {
                left: 9%;
                width: 150px;
                flex-wrap: wrap;
                margin: 20px 0 40px 0;

                padding: 15px;
                margin-left: 170px;
        }
}

@media (max-width: 320px) {
        #game-container {
                display: flex;
                flex-direction: column;
                width: 100%;
                height: 100vh;
                margin: 10px auto;
                padding: 5px;
                align-items: center;
                background:#ebfcfc;


        }

        #letters-container {
                width: 270px;
                flex-wrap: wrap;
                margin-bottom: 20px;
        }
        #word-container {
                font-size: 20px;
        }
        .letter-btn {
                margin: 2px;
                padding: 2px 5px;
        }
        #message {
                font-weight: bold;
                font-size: 15px;
        }
        #restart-btn {
                font-size: medium;
                padding: 2px 5px;
        }
        #hangman-img {
                width: 120px;
                height: 120px;
                margin: 15px 0 0px 0;
        }
        #clue {
                margin-top: 10px;
                font-size: 18px;
        }

        #tries {
                left: 20%;
                margin: 2px;
                padding: 15px 0 0 0;

        }
}* {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
}
body {
        font-family: Arial, sans-serif;
        line-height: 1.6;
        text-align: center;
        justify-content: center;
        display: flex;
        color: #333;
        background: linear-gradient(to bottom, #a8edea, #fed6e3);
        align-items: center;
        margin: 0;
        height: 100vh;
        /* background-color: #f9f9f9; */
}

#game-container {
        display: flex;
        flex-direction: column;
        width: 80%;
        margin: 50px auto;
        padding: 20px;
        border: 1px solid #ccc;
        border-radius: 10px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        /* justify-content: center; */
        align-items: center;
        background: rgba(255, 255, 255, 0.8);
        text-align: center;
}
h1 {
        font-family: "Pacifico", cursive;
        color: #ff6f61;
}
#word-container {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 20px;
}

.logo {
        height: 80px;
        width: 83px;
}
.letter-btn {
        margin: 10px;
        padding: 10px 20px;
        border: none;
        border-radius: 8px;
        color: #fff;
        background: #ff6f61;
        cursor: pointer;
        transition: background 0.3s ease;
}
.letter-btn:hover {
        background-color: #ff402e;
}
.letter-btn.disabled {
        background-color: #ccc;
        cursor: not-allowed;
}

#message {
        font-size: 18px;
        font-weight: bold;
        color: #666;
        margin-bottom: 20px;
}

#restart-btn {
        font-weight: bold;
        padding: 10px 20px;
        border: none;
        border-radius: 10px;
        background-color: #ff6f61;
        color: #fff;
        cursor: pointer;
        margin-bottom: 20px;
}
#restart-btn:hover {
        background-color: #ff402e;
}
#hangman-img {
        width: 180px;
        height: 180px;
        margin: 0 20px;
        transition: transform 0.3s ease-in-out;
}
.hangman-image:hover {
        transform: scale(1.05);
}


#clue {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
        color: darkblue;

}

#tries {
        position: relative;
        left: 30%;
        margin: 10px;

        /* margin-left: 900px; */
        padding: 10px 20px;
        border: none;
        border-radius: 10px;
        background-color: #4fd8d8;
        color: #fff;
        cursor: pointer;
}
/* Media Queries */

/* Small screens (max-width: 768px) */
@media (max-width: 768px) {
        #game-container {
                display: flex;
                flex-direction: column;
                width: 90%;
                margin: 20px auto;
                height: 100vh;
                padding: 10px;
                align-items: center;
        }
        #word-container {
                font-size: 18px;
        }
        .letter-btn {
                margin: 5px;
                padding: 5px 10px;
        }
        #letters-container {
                width: 350px;
        }
        #message {
                font-size: 14px;
                font-weight: bold;
        }
        #restart-btn {
                height: 30px;
                padding: 5px 10px;
        }
        #hangman-img {
                width: 120px;
                height: 120px;
        }
        #clue {
                font-size: 14px;
        }

        #tries {
                /* margin: 5px; */
                left: 30%;
                padding: 13px 5px 10px 5px;
        }
}

/* Extra small screens (max-width: 480px) */
@media (max-width: 480px) {
        #game-container {
                display: flex;
                flex-direction: column;
                width: 100%;
                height: 100vh;
                margin: 10px auto;
                padding: 5px;
                align-items: center;
                background:#ebfcfc;

        }

        #letters-container {
                /* width: 280px; */
                flex-wrap: wrap;
                margin-bottom: 30px;
        }
        #word-container {
                font-size: 20px;

        }
        .letter-btn {
                height: 30px;
                width: 30px;
                border-radius: 100%;
                margin: 2px;
                padding: 2px 5px;
        }
        #message {
                font-weight: bold;
                font-size: 30px;
                margin: 10px 0 10px 0;
        }
        #restart-btn {
                margin-top: 30px;
                height: 40px;
                font-size: 20px;
                padding: 2px 5px;
        }
        #hangman-img {
                width: 170px;
                height: 170px;
                margin: 30px 0 0px 0;
        }
        #clue {
                margin-top: 40px;
                font-size: 21px;
        }

        #tries {
                left: 9%;
                width: 150px;
                flex-wrap: wrap;
                margin: 20px 0 40px 0;

                padding: 15px;
                margin-left: 170px;
        }
}

@media (max-width: 320px) {
        #game-container {
                display: flex;
                flex-direction: column;
                width: 100%;
                height: 100vh;
                margin: 10px auto;
                padding: 5px;
                align-items: center;
                background:#ebfcfc;


        }

        #letters-container {
                width: 270px;
                flex-wrap: wrap;
                margin-bottom: 20px;
        }
        #word-container {
                font-size: 20px;
        }
        .letter-btn {
                margin: 2px;
                padding: 2px 5px;
        }
        #message {
                font-weight: bold;
                font-size: 15px;
        }
        #restart-btn {
                font-size: medium;
                padding: 2px 5px;
        }
        #hangman-img {
                width: 120px;
                height: 120px;
                margin: 15px 0 0px 0;
        }
        #clue {
                margin-top: 10px;
                font-size: 18px;
        }

        #tries {
                left: 20%;
                margin: 2px;
                padding: 15px 0 0 0;

        }
}

JavaScript
was used majorly for the conditionals and interactivity of the game.

const languages = ["javascript", "python", "java", "ruby"];
const frameworks = ["react", "angular", "vue", "django", "flask"];
const tools = ["git", "webpack", "babel", "eslint", "prettier"];
const concept = ["closure", "callback", "promises", "async", "hosting"];
const databases = ["mongodb", "sqlite", "mysql"];

const allObjects = {languages, frameworks, tools, concept, databases};

let chosenWord = "";
let guessedLetters = [];
let wrongGuesses;

const wordContainer = document.getElementById("word-container");
const lettersContainer = document.getElementById("letters-container");
const message = document.getElementById("message");
const restartBtn = document.getElementById("restart-btn");
const hangmanImg = document.getElementById("hangman-img");
const hangmanAud = document.getElementById("hangman-aud");
const trials = document.getElementById("tries");
const clue = document.getElementById("clue");
function init() {
        const randomArray =
                Object.values(allObjects)[
                        Math.floor(Math.random() * Object.keys(allObjects).length)
                ];

        const randomValue =
                randomArray[Math.floor(Math.random() * randomArray.length)];
        console.log(randomValue);
        const getClue = () => {
                for (const [key, value] of Object.entries(allObjects)) {
                        if (value.includes(randomValue)) {
                                return key;
                        }
                }
        };
        clue.textContent = `Clue: "${getClue().toUpperCase()}" in Programming`;
        chosenWord = randomValue;
        // words[Math.floor(Math.random() * words.length)];
        guessedLetters = [];
        remainingGuesses = 5;
        message.textContent = "";
        wordContainer.innerHTML = "_ ".repeat(chosenWord.length).trim();
        lettersContainer.innerHTML = "";
        hangmanImg.src = "hangmanSteady.png";
        trials.innerText = "YOU HAVE 5 TRIALS!";
        wrongGuesses = 0;
        for (let i = 65; i  {
                button.classList.add("disabled");
                button.disabled = true;
        });
}

restartBtn.addEventListener("click", init);

init();
//this handles guesses 

function handleGuess(event) {
        const letter = event.target.innerText.toLowerCase();
        event.target.classList.add("disabled");
        event.target.disabled = true;

        if (chosenWord.includes(letter)) {
                guessedLetters.push(letter);
                const displayWord = chosenWord
                        .split("")
                        .map((letter) => (guessedLetters.includes(letter) ? letter : "_"))
                        .join(" ");
                wordContainer.textContent = displayWord;
        } else {
                wrongGuesses  ;
                if (wrongGuesses === 1) {
                        trials.innerText = "4 trials left";
                        hangmanImg.src = "hangman1.png";
                        hangmanAud.src = "failed.mp3";
                        hangmanAud.play();
                } else if (wrongGuesses === 2) {
                        hangmanImg.src = "hangman2.png";
                        trials.innerText = "3 trials left";
                        hangmanAud.src = "failed.mp3";
                        hangmanAud.play();
                } else if (wrongGuesses === 3) {
                        hangmanImg.src = "hangman3.png";
                        trials.innerText = "2 trials left";
                        hangmanAud.src = "failed.mp3";
                        hangmanAud.play();
                } else if (wrongGuesses === 4) {
                        hangmanImg.src = "hangman4.png";
                        trials.innerText = "1 trials left";
                        hangmanAud.src = "failed.mp3";
                        hangmanAud.play();
                }
        }

        handleGameOver();
}

const handleGameOver = () => {
        if (wrongGuesses === 5) {
                message.textContent = `Game Over! ❌ The word was  "${chosenWord}".`;
                disableAllButtons();
                hangmanImg.src = "hangmanFailed.png";
                trials.innerText = "0 TRIAL!";
                hangmanAud.src = "gameover.mp3";
                hangmanAud.play();
                document.querySelector("#message").style.color = "red";
        }
        if (chosenWord.split("").every((letter) => guessedLetters.includes(letter))) {
                message.textContent = "Congratulations! You guessed the word!";
                hangmanImg.src = "hangmanSuccess.png";
                trials.innerText = "Congrats!";
                hangmanAud.src = "success.mp3";
                hangmanAud.play();
                document.querySelector("#message").style.color = "green";

                disableAllButtons();
        }
};

Code Explanation;
I created an object of arrays. The array names serve as the clue to the word. The game is such that it randomly loops into the objects then gets a single array, for example if after it loops and finally gets the languages array. It then randomly loops over the language array and hides the guess. Hence the player only has a clue of what is to be guessed . So if the guessed word is “python”. The player gets to attempt to guess the word. If after 5 failed attempts of guesses, you failed the game and will have to restart. But if you get the word without 5 failed attempts you get a congratulation message.
The addition of images and audio makes the game intriguing making it much more interactive.

Conclusion
Developing this Hangman game was a rewarding experience that allowed me to apply and enhance my skills in JavaScript. The game’s features, including trial tracking, clues, dynamic images, and feedback messages, create an engaging and interactive experience for players. Deploying the game on Vercel ensures it is accessible and shareable, showcasing the capabilities of modern web development tools and practices.

Future Advancement.
I would be looking forward to adding new characteristics to the game in the future to implement.

  • A score keeper section: it basically stores the amount of success and failures and it returns the total score over 10. For example if you get 6 wrong attempts you get 4/10.

  • Timer ⌛: I implement a timer, for example for each guess you get 15 seconds if after 5 second you fail to input a word, you automatically get a failed attempt. To improve the difficulty of the game.

Future implementation
The MTnD Hangman game can be used in different niches, only left for me to tailor the objects to your niche, the only things I’ll be needing are keywords that align with your specific niche. The MTnD hangman could be applied in the following;

  1. Educational Hangman: Tailor the game for specific subjects like math, science, or history, where players guess terms related to these topics.
  2. Themed Hangman: Create themes such as movies, books, or famous personalities for each game session.
  3. Multilingual Hangman: Offer versions in different languages to help with language learning.
  4. Custom Word Lists: Allow users to upload or create their own word lists for a personalized experience.
  5. Difficulty Levels: Include options for easy, medium, and hard difficulty levels based on word length or complexity.
  6. Story Mode: Incorporate a storyline or progress system where players unlock new levels or challenges as they succeed.

Each niche could provide a unique twist to the MTnD Hangman game and attract different audiences.
I would be open to suggestions on this project.

版本聲明 本文轉載於:https://dev.to/miller4tech/creating-a-dynamic-hangman-game-with-javascript-a-technical-overview-15i5?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 適用於 Java 的 Jupyter 筆記本
    適用於 Java 的 Jupyter 筆記本
    Jupyter Notebook 的强大 Jupyter Notebooks 是一个出色的工具,最初是为了帮助数据科学家和工程师使用 python 编程语言简化数据处理工作而开发的。事实上,笔记本的交互性使其非常适合快速查看代码结果,而无需搭建开发环境、编译、打包等。此功能对于数据...
    程式設計 發佈於2024-11-06
  • 如何在 PyQt 中的主視窗和執行緒之間共享資料:直接引用與訊號和插槽?
    如何在 PyQt 中的主視窗和執行緒之間共享資料:直接引用與訊號和插槽?
    PyQt 中主視窗與執行緒之間共享資料多執行緒應用程式通常需要在主視窗執行緒與工作執行緒之間共用數據。為了確保線程安全和正確的通信,PyQt 提供了幾種實用的方法。 選項 1:直接引用主視窗在此方法中,對主視窗的引用視窗被傳遞給執行緒。然後執行緒可以直接存取主視窗中的數據,例如 spinbox 的值...
    程式設計 發佈於2024-11-06
  • 對於專業開發人員來說最有用的 VS Code 快捷方式?
    對於專業開發人員來說最有用的 VS Code 快捷方式?
    VS Code 中 20 個最有用的快捷鍵 一般導航 指令面板:存取 VS Code 中的所有可用指令。 Ctrl Shift P (Windows/Linux) 或 Cmd Shift P (macOS) 快速開啟:按名稱快速開啟檔案。 Ctrl P (Windows/Linux) 或 Cmd ...
    程式設計 發佈於2024-11-06
  • 何時使用“composer update”與“composer install”?
    何時使用“composer update”與“composer install”?
    探索composer update和composer install之間的區別Composer是一個流行的PHP依賴管理器,提供兩個關鍵命令:composer update和composer install。雖然它們具有管理依賴關係的共同目標,但它們具有不同的目的並以不同的方式運作。 Compose...
    程式設計 發佈於2024-11-06
  • Python 中的物件導向程式設計 (OOP):類別和物件解釋
    Python 中的物件導向程式設計 (OOP):類別和物件解釋
    面向对象编程 (OOP) 是软件开发中使用的关键方法。 在本文中,我们将探讨 OOP 的主要思想,特别是 Python 中的类、对象、继承和多态性。 在本指南结束时,您将了解如何使用 OOP 原则组织 Python 代码,使您的程序更加模块化、可重用且更易于维护。 什么是面向对象编...
    程式設計 發佈於2024-11-06
  • 在 Git 中切換分支而不丟失您的工作
    在 Git 中切換分支而不丟失您的工作
    作为开发人员,我们经常发现自己处于这样的情况:当我们深入编写功能时,突然有一个紧急问题需要我们立即关注。为了解决这个问题,我们需要切换 Git 中的分支。但是,如果我们尚未提交当前的更改,那么这样做可能会有风险。我们可能会失去工作或面临合并冲突。 在这篇文章中,我将引导您了解两种在 Git 中切换分...
    程式設計 發佈於2024-11-06
  • shell 中的 Props 與回呼
    shell 中的 Props 與回呼
    在這篇文章中,我將帶您了解一個實際場景,其中父元件(ListBox) 與子元件(AlertComponent ) 使用props 和回呼。 當您希望子元件與父元件通訊以維護狀態或觸發操作時,這在 React 中非常有用。 讓我們透過這個例子來理解: 我有一個 ListBox 元件,用於顯示項目清...
    程式設計 發佈於2024-11-06
  • 如何使用 Python 的 argparse 模組將值列表作為命令列參數傳遞?
    如何使用 Python 的 argparse 模組將值列表作為命令列參數傳遞?
    如何使用 argparse 將清單作為命令列參數傳遞? 在 Python 的 argparse 模組中,您可以傳遞清單使用 nargs 或附加選項作為命令列參數。 nargs使用 nargs 指定期望的參數數量。例如,nargs=' 表示一個或多個參數,nargs='*' 表...
    程式設計 發佈於2024-11-06
  • 如何解決 ES6 模組中的「意外令牌匯出」錯誤?
    如何解決 ES6 模組中的「意外令牌匯出」錯誤?
    意外的令牌導出:擁抱ES6 模組支援嘗試執行ES6 程式碼時遇到「意外的代幣匯出」錯誤可能會令人困惑問題。當執行時間環境缺乏對您正在使用的 EcmaScript 模組 (ESM) 語法的支援時,就會發生此錯誤。 了解 ESM:ESM,通常稱為「ES6 Modules」引入了 JavaScript 的...
    程式設計 發佈於2024-11-06
  • Next.js 簡介:建立您的第一個應用程式
    Next.js 簡介:建立您的第一個應用程式
    Next.js 是一种流行的 React 框架,使开发人员能够创建快速的服务器渲染应用程序。它提供了强大的开箱即用功能,例如静态站点生成 (SSG)、服务器端渲染 (SSR) 和 API 路由。在本指南中,我们将逐步介绍构建您的第一个 Next.js 应用程序的过程,重点关注关键概念和实际示例。 ...
    程式設計 發佈於2024-11-06
  • 使用 ChatGPT 建立訂單處理服務(貢獻努力)並已完成
    使用 ChatGPT 建立訂單處理服務(貢獻努力)並已完成
    人工智能为改变和提高我的日常工作效率做出了贡献 作为一名开发人员,当您的时间有限时,构建订单处理服务有时会让人感到不知所措。然而,借助 ChatGPT 等人工智能驱动的开发工具的强大功能,您可以通过生成代码、设计实体和逐步解决问题来显着加快流程。在本文中,我将向您介绍如何使用 ChatGPT 在短短...
    程式設計 發佈於2024-11-06
  • 如何在 Django 中記錄所有 SQL 查詢?
    如何在 Django 中記錄所有 SQL 查詢?
    如何在 Django 中記錄 SQL 查詢記錄 Django 應用程式執行的所有 SQL 查詢有利於偵錯和效能分析。本文提供了有關如何有效實現此目標的逐步指南。 配置要記錄所有SQL 查詢,包括管理網站產生的查詢,請將以下程式碼片段整合到settings.py 檔案中的LOGGING 欄位:LOGG...
    程式設計 發佈於2024-11-06
  • JavaScript 是同步還是異步,是單執行緒還是多執行緒? JavaScript程式碼是如何執行的?
    JavaScript 是同步還是異步,是單執行緒還是多執行緒? JavaScript程式碼是如何執行的?
    JavaScript 是一種同步、單執行緒語言,一次只能執行一個指令。僅噹噹前行執行完畢後,才會移至下一行。但是,JavaScript 可以使用事件循環、Promises、Async/Await 和回呼佇列執行非同步操作(JavaScript 預設是同步的)。 JavaScript程式碼是如何執行...
    程式設計 發佈於2024-11-06
  • 如何從 PHP 中的物件數組中提取一列屬性?
    如何從 PHP 中的物件數組中提取一列屬性?
    PHP:從物件數組中高效提取一列屬性許多程式設計場景都涉及使用物件數組,其中每個物件可能有多個屬性。有時,需要從每個物件中提取特定屬性以形成單獨的陣列。在 PHP 中,在不借助循環或外部函數的情況下用一行程式碼實現此目標可能很棘手。 一個可能的方法是利用 array_walk() 函數和 creat...
    程式設計 發佈於2024-11-06

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3