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
浏览:404

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]删除
最新教程 更多>
  • 为什么我的CSS背景图像出现?
    为什么我的CSS背景图像出现?
    故障排除:CSS背景图像未出现 ,您的背景图像尽管遵循教程说明,但您的背景图像仍未加载。图像和样式表位于相同的目录中,但背景仍然是空白的白色帆布。而不是不弃用的,您已经使用了CSS样式: bockent {背景:封闭图像文件名:背景图:url(nickcage.jpg); 如果您的html,css...
    编程 发布于2025-07-12
  • 如何限制动态大小的父元素中元素的滚动范围?
    如何限制动态大小的父元素中元素的滚动范围?
    在交互式接口中实现垂直滚动元素的CSS高度限制,控制元素的滚动行为对于确保用户体验和可访问性是必不可少的。一种这样的方案涉及限制动态大小的父元素中元素的滚动范围。问题:考虑一个布局,其中我们具有与用户垂直滚动一起移动的可滚动地图div,同时与固定的固定sidebar保持一致。但是,地图的滚动无限期...
    编程 发布于2025-07-12
  • 为什么我在Silverlight Linq查询中获得“无法找到查询模式的实现”错误?
    为什么我在Silverlight Linq查询中获得“无法找到查询模式的实现”错误?
    查询模式实现缺失:解决“无法找到”错误在银光应用程序中,尝试使用LINQ建立错误的数据库连接的尝试,无法找到以查询模式的实现。”当省略LINQ名称空间或查询类型缺少IEnumerable 实现时,通常会发生此错误。 解决问题来验证该类型的质量是至关重要的。在此特定实例中,tblpersoon可能需...
    编程 发布于2025-07-12
  • 版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    在时间戳列上使用current_timestamp或MySQL版本中的current_timestamp或在5.6.5 此限制源于遗留实现的关注,这些限制需要对当前的_timestamp功能进行特定的实现。 创建表`foo`( `Productid` int(10)unsigned not n...
    编程 发布于2025-07-12
  • 如何将PANDAS DataFrame列转换为DateTime格式并按日期过滤?
    如何将PANDAS DataFrame列转换为DateTime格式并按日期过滤?
    Transform Pandas DataFrame Column to DateTime FormatScenario:Data within a Pandas DataFrame often exists in various formats, including strings.使用时间数据时...
    编程 发布于2025-07-12
  • `console.log`显示修改后对象值异常的原因
    `console.log`显示修改后对象值异常的原因
    foo = [{id:1},{id:2},{id:3},{id:4},{id:id:5},],]; console.log('foo1',foo,foo.length); foo.splice(2,1); console.log('foo2', foo, foo....
    编程 发布于2025-07-12
  • Python中嵌套函数与闭包的区别是什么
    Python中嵌套函数与闭包的区别是什么
    嵌套函数与python 在python中的嵌套函数不被考虑闭合,因为它们不符合以下要求:不访问局部范围scliables to incling scliables在封装范围外执行范围的局部范围。 make_printer(msg): DEF打印机(): 打印(味精) ...
    编程 发布于2025-07-12
  • 图片在Chrome中为何仍有边框?`border: none;`无效解决方案
    图片在Chrome中为何仍有边框?`border: none;`无效解决方案
    在chrome 中删除一个频繁的问题时,在与Chrome and IE9中的图像一起工作时,遇到了一个频繁的问题。和“边境:无;”在CSS中。要解决此问题,请考虑以下方法: Chrome具有忽略“ border:none; none;”的已知错误,风格。要解决此问题,请使用以下CSS ID块创建带...
    编程 发布于2025-07-12
  • PHP SimpleXML解析带命名空间冒号的XML方法
    PHP SimpleXML解析带命名空间冒号的XML方法
    在php 很少,请使用该限制很大,很少有很高。例如:这种技术可确保可以通过遍历XML树和使用儿童()方法()方法的XML树和切换名称空间来访问名称空间内的元素。
    编程 发布于2025-07-12
  • 人脸检测失败原因及解决方案:Error -215
    人脸检测失败原因及解决方案:Error -215
    错误处理:解决“ error:( - 215)!empty()in Function openCv in Function MultSiscale中的“检测”中的错误:在功能检测中。”当Face Cascade分类器(即面部检测至关重要的组件)未正确加载时,通常会出现此错误。要解决此问题,必须...
    编程 发布于2025-07-12
  • 编译器报错“usr/bin/ld: cannot find -l”解决方法
    编译器报错“usr/bin/ld: cannot find -l”解决方法
    错误:“ usr/bin/ld:找不到-l “ 此错误表明链接器在链接您的可执行文件时无法找到指定的库。为了解决此问题,我们将深入研究如何指定库路径并将链接引导到正确位置的详细信息。添加库搜索路径的一个可能的原因是,此错误是您的makefile中缺少库搜索路径。要解决它,您可以在链接器命令中添加...
    编程 发布于2025-07-12
  • 如何简化PHP中的JSON解析以获取多维阵列?
    如何简化PHP中的JSON解析以获取多维阵列?
    php 试图在PHP中解析JSON数据的JSON可能具有挑战性,尤其是在处理多维数组时。 To simplify the process, it's recommended to parse the JSON as an array rather than an object.To do...
    编程 发布于2025-07-12
  • 查找当前执行JavaScript的脚本元素方法
    查找当前执行JavaScript的脚本元素方法
    如何引用当前执行脚本的脚本元素在某些方案中理解问题在某些方案中,开发人员可能需要将其他脚本动态加载其他脚本。但是,如果Head Element尚未完全渲染,则使用document.getElementsbytagname('head')[0] .appendChild(v)的常规方...
    编程 发布于2025-07-12
  • eval()vs. ast.literal_eval():对于用户输入,哪个Python函数更安全?
    eval()vs. ast.literal_eval():对于用户输入,哪个Python函数更安全?
    称量()和ast.literal_eval()中的Python Security 在使用用户输入时,必须优先确保安全性。强大的Python功能Eval()通常是作为潜在解决方案而出现的,但担心其潜在风险。 This article delves into the differences betwee...
    编程 发布于2025-07-12
  • 在GO中构造SQL查询时,如何安全地加入文本和值?
    在GO中构造SQL查询时,如何安全地加入文本和值?
    在go中构造文本sql查询时,在go sql queries 中,在使用conting and contement和contement consem per时,尤其是在使用integer per当per当per时,per per per当per. 在GO中实现这一目标的惯用方法是使用fmt.spr...
    编程 发布于2025-07-12

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3