Hangman Game – CodingNepal https://www.codingnepalweb.com CodingNepal is a blog dedicated to providing valuable and informative content about web development technologies such as HTML, CSS, JavaScript, and PHP. Wed, 09 Aug 2023 14:01:07 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 Build A Hangman Game in HTML CSS and JavaScript https://www.codingnepalweb.com/build-hangman-game-html-javascript/ https://www.codingnepalweb.com/build-hangman-game-html-javascript/#respond Fri, 21 Jul 2023 18:16:51 +0000 https://www.codingnepalweb.com/?p=5678 Build A Hangman Game in HTML CSS and JavaScript

Hangman is the classic word-guessing game you’ve likely enjoyed playing. But as a beginner web developer, have you ever thought about building your own Hangman game? Building a hangman game is not only fun and engaging but also provides an excellent opportunity to enhance your web development and problem-solving skills.

If you’re unfamiliar, Hangman is a word-guessing game where players try to guess all the letters of a randomly generated word within a given number of tries. There is also a hangman illustration that will progressively appear on the gallows for each incorrect guess.

In this beginner-friendly blog post, I’ll show you how to build a Hangman game in HTML, CSS, and JavaScript. By creating this game, you’ll gain practical experience and dive into essential concepts of web development, such as DOM manipulation, event handling, conditional statements, array usage, and many more.

Video Tutorial of Hangman Game HTML & JavaScript

If you enjoy learning through video tutorials, the above YouTube video is an excellent resource. In the video, I’ve explained each line of code and provided informative comments to make the process of building your own Hangman game beginner-friendly and easy to follow.

However, if you like reading blog posts or want a step-by-step guide for building this game, you can continue reading this post. By the end of this post, you’ll have your own Hangman game that you can play or show off to your friends.

Steps to Build Hangman Game in HTML & JavaScript

To build a Hangman game using HTML, CSS, and JavaScript, follow these step-by-step instructions:

  1. Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a scripts folder with word-list.js and script.js files. The extension of the files must be .js and files should be inside the scripts folder.
  5. Download and place the Images folder in your project directory. This folder includes the necessary images and gifs for the game.

To start, add the following HTML codes to your index.html file. These codes include essential HTML elements, such as a modal box and a container for the game. Using JavaScript later, we’ll add or modify these elements and randomize game letters, hints, and keyboard keys.

<!DOCTYPE html>
<!-- Coding By CodingNepal - www.codingnepalweb.com -->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hangman Game JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <script src="scripts/word-list.js" defer></script>
    <script src="scripts/script.js" defer></script>
</head>
<body>
    <div class="game-modal">
        <div class="content">
            <img src="#" alt="gif">
            <h4>Game Over!</h4>
            <p>The correct word was: <b>rainbow</b></p>
            <button class="play-again">Play Again</button>
        </div>
    </div>
    <div class="container">
        <div class="hangman-box">
            <img src="#" draggable="false" alt="hangman-img">
            <h1>Hangman Game</h1>
        </div>
        <div class="game-box">
            <ul class="word-display"></ul>
            <h4 class="hint-text">Hint: <b></b></h4>
            <h4 class="guesses-text">Incorrect guesses: <b></b></h4>
            <div class="keyboard"></div>
        </div>
    </div>
</body>
</html>

Next, add the following CSS codes to your style.css file to apply visual styling to your game: color, font, border, background, etc. Now, if you load the web page in your browser, you will see the Hangman game with its various styled elements. You can play around with colors, fonts, borders, backgrounds, and more to give your Hangman game a unique and appealing look.

/* Importing Google font - Open Sans */
@import url("https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;500;600;700&display=swap");
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: "Open Sans", sans-serif;
}
body {
    display: flex;
    padding: 0 10px;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    background: #5E63BA;
}
.container {
    display: flex;
    width: 850px;
    gap: 70px;
    padding: 60px 40px;
    background: #fff;
    border-radius: 10px;
    align-items: flex-end;
    justify-content: space-between;
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}
.hangman-box img {
    user-select: none;
    max-width: 270px;
}
.hangman-box h1 {
    font-size: 1.45rem;
    text-align: center;
    margin-top: 20px;
    text-transform: uppercase;
}
.game-box .word-display {
    gap: 10px;
    list-style: none;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}
.word-display .letter {
    width: 28px;
    font-size: 2rem;
    text-align: center;
    font-weight: 600;
    margin-bottom: 40px;
    text-transform: uppercase;
    border-bottom: 3px solid #000;
}
.word-display .letter.guessed {
    margin: -40px 0 35px;
    border-color: transparent;
}
.game-box h4 {
    text-align: center;
    font-size: 1.1rem;
    font-weight: 500;
    margin-bottom: 15px;
}
.game-box h4 b {
    font-weight: 600;
}
.game-box .guesses-text b {
    color: #ff0000;
}
.game-box .keyboard {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
    margin-top: 40px;
    justify-content: center;
}
:where(.game-modal, .keyboard) button {
    color: #fff;
    border: none;
    outline: none;
    cursor: pointer;
    font-size: 1rem;
    font-weight: 600;
    border-radius: 4px;
    text-transform: uppercase;
    background: #5E63BA;
}
.keyboard button {
    padding: 7px;
    width: calc(100% / 9 - 5px);
}
.keyboard button[disabled] {
    pointer-events: none;
    opacity: 0.6;
}
:where(.game-modal, .keyboard) button:hover {
    background: #8286c9;
}
.game-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    pointer-events: none;
    background: rgba(0,0,0,0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    padding: 0 10px;
    transition: opacity 0.4s ease;
}
.game-modal.show {
    opacity: 1;
    pointer-events: auto;
    transition: opacity 0.4s 0.4s ease;
}
.game-modal .content {
    padding: 30px;
    max-width: 420px;
    width: 100%;
    border-radius: 10px;
    background: #fff;
    text-align: center;
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}
.game-modal img {
    max-width: 130px;
    margin-bottom: 20px;
}
.game-modal img[src="images/victory.gif"] {
    margin-left: -10px;
}
.game-modal h4 {
    font-size: 1.53rem;
}
.game-modal p {
    font-size: 1.15rem;
    margin: 15px 0 30px;
    font-weight: 500;
}
.game-modal p b {
    color: #5E63BA;
    font-weight: 600;
}
.game-modal button {
    padding: 12px 23px;
}

@media (max-width: 782px) {
    .container {
        flex-direction: column;
        padding: 30px 15px;
        align-items: center;
    }
    .hangman-box img {
        max-width: 200px;
    }
    .hangman-box h1 {
        display: none;
    }
    .game-box h4 {
        font-size: 1rem;
    }
    .word-display .letter {
        margin-bottom: 35px;
        font-size: 1.7rem;
    }
    .word-display .letter.guessed {
        margin: -35px 0 25px;
    }
    .game-modal img {
        max-width: 120px;
    }
    .game-modal h4 {
        font-size: 1.45rem;
    }
    .game-modal p {
        font-size: 1.1rem;
    }
    .game-modal button {
        padding: 10px 18px;
    }
}

Next, add the following JavaScript code to your word-list.js file: This script includes a list of various words along with corresponding hints. Feel free to expand this list to make your Hangman game even more enjoyable and challenging for players.

const wordList = [
    {
        word: "guitar",
        hint: "A musical instrument with strings."
    },
    {
        word: "oxygen",
        hint: "A colorless, odorless gas essential for life."
    },
    {
        word: "mountain",
        hint: "A large natural elevation of the Earth's surface."
    },
    {
        word: "painting",
        hint: "An art form using colors on a surface to create images or expression."
    },
    {
        word: "astronomy",
        hint: "The scientific study of celestial objects and phenomena."
    },
    {
        word: "football",
        hint: "A popular sport played with a spherical ball."
    },
    {
        word: "chocolate",
        hint: "A sweet treat made from cocoa beans."
    },
    {
        word: "butterfly",
        hint: "An insect with colorful wings and a slender body."
    },
    {
        word: "history",
        hint: "The study of past events and human civilization."
    },
    {
        word: "pizza",
        hint: "A savory dish consisting of a round, flattened base with toppings."
    },
    {
        word: "jazz",
        hint: "A genre of music characterized by improvisation and syncopation."
    },
    {
        word: "camera",
        hint: "A device used to capture and record images or videos."
    },
    {
        word: "diamond",
        hint: "A precious gemstone known for its brilliance and hardness."
    },
    {
        word: "adventure",
        hint: "An exciting or daring experience."
    },
    {
        word: "science",
        hint: "The systematic study of the structure and behavior of the physical and natural world."
    },
    {
        word: "bicycle",
        hint: "A human-powered vehicle with two wheels."
    },
    {
        word: "sunset",
        hint: "The daily disappearance of the sun below the horizon."
    },
    {
        word: "coffee",
        hint: "A popular caffeinated beverage made from roasted coffee beans."
    },
    {
        word: "dance",
        hint: "A rhythmic movement of the body often performed to music."
    },
    {
        word: "galaxy",
        hint: "A vast system of stars, gas, and dust held together by gravity."
    },
    {
        word: "orchestra",
        hint: "A large ensemble of musicians playing various instruments."
    },
    {
        word: "volcano",
        hint: "A mountain or hill with a vent through which lava, rock fragments, hot vapor, and gas are ejected."
    },
    {
        word: "novel",
        hint: "A long work of fiction, typically with a complex plot and characters."
    },
    {
        word: "sculpture",
        hint: "A three-dimensional art form created by shaping or combining materials."
    },
    {
        word: "symphony",
        hint: "A long musical composition for a full orchestra, typically in multiple movements."
    },
    {
        word: "architecture",
        hint: "The art and science of designing and constructing buildings."
    },
    {
        word: "ballet",
        hint: "A classical dance form characterized by precise and graceful movements."
    },
    {
        word: "astronaut",
        hint: "A person trained to travel and work in space."
    },
    {
        word: "waterfall",
        hint: "A cascade of water falling from a height."
    },
    {
        word: "technology",
        hint: "The application of scientific knowledge for practical purposes."
    },
    {
        word: "rainbow",
        hint: "A meteorological phenomenon that is caused by reflection, refraction, and dispersion of light."
    },
    {
        word: "universe",
        hint: "All existing matter, space, and time as a whole."
    },
    {
        word: "piano",
        hint: "A musical instrument played by pressing keys that cause hammers to strike strings."
    },
    {
        word: "vacation",
        hint: "A period of time devoted to pleasure, rest, or relaxation."
    },
    {
        word: "rainforest",
        hint: "A dense forest characterized by high rainfall and biodiversity."
    },
    {
        word: "theater",
        hint: "A building or outdoor area in which plays, movies, or other performances are staged."
    },
    {
        word: "telephone",
        hint: "A device used to transmit sound over long distances."
    },
    {
        word: "language",
        hint: "A system of communication consisting of words, gestures, and syntax."
    },
    {
        word: "desert",
        hint: "A barren or arid land with little or no precipitation."
    },
    {
        word: "sunflower",
        hint: "A tall plant with a large yellow flower head."
    },
    {
        word: "fantasy",
        hint: "A genre of imaginative fiction involving magic and supernatural elements."
    },
    {
        word: "telescope",
        hint: "An optical instrument used to view distant objects in space."
    },
    {
        word: "breeze",
        hint: "A gentle wind."
    },
    {
        word: "oasis",
        hint: "A fertile spot in a desert where water is found."
    },
    {
        word: "photography",
        hint: "The art, process, or practice of creating images by recording light or other electromagnetic radiation."
    },
    {
        word: "safari",
        hint: "An expedition or journey, typically to observe wildlife in their natural habitat."
    },
    {
        word: "planet",
        hint: "A celestial body that orbits a star and does not produce light of its own."
    },
    {
        word: "river",
        hint: "A large natural stream of water flowing in a channel to the sea, a lake, or another such stream."
    },
    {
        word: "tropical",
        hint: "Relating to or situated in the region between the Tropic of Cancer and the Tropic of Capricorn."
    },
    {
        word: "mysterious",
        hint: "Difficult or impossible to understand, explain, or identify."
    },
    {
        word: "enigma",
        hint: "Something that is mysterious, puzzling, or difficult to understand."
    },
    {
        word: "paradox",
        hint: "A statement or situation that contradicts itself or defies intuition."
    },
    {
        word: "puzzle",
        hint: "A game, toy, or problem designed to test ingenuity or knowledge."
    },
    {
        word: "whisper",
        hint: "To speak very softly or quietly, often in a secretive manner."
    },
    {
        word: "shadow",
        hint: "A dark area or shape produced by an object blocking the light."
    },
    {
        word: "secret",
        hint: "Something kept hidden or unknown to others."
    },
    {
        word: "curiosity",
        hint: "A strong desire to know or learn something."
    },
    {
        word: "unpredictable",
        hint: "Not able to be foreseen or known beforehand; uncertain."
    },
    {
        word: "obfuscate",
        hint: "To confuse or bewilder someone; to make something unclear or difficult to understand."
    },
    {
        word: "unveil",
        hint: "To make known or reveal something previously secret or unknown."
    },
    {
        word: "illusion",
        hint: "A false perception or belief; a deceptive appearance or impression."
    },
    {
        word: "moonlight",
        hint: "The light from the moon."
    },
    {
        word: "vibrant",
        hint: "Full of energy, brightness, and life."
    },
    {
        word: "nostalgia",
        hint: "A sentimental longing or wistful affection for the past."
    },
    {
        word: "brilliant",
        hint: "Exceptionally clever, talented, or impressive."
    },
];

Finally, add the following JavaScript code to your script.js file. This script code will be responsible for the game’s logic, including generating a random word, managing user input, keeping track of guessed letters, checking for correct guesses, and updating the hangman’s visual representation as the game progresses.

const wordDisplay = document.querySelector(".word-display");
const guessesText = document.querySelector(".guesses-text b");
const keyboardDiv = document.querySelector(".keyboard");
const hangmanImage = document.querySelector(".hangman-box img");
const gameModal = document.querySelector(".game-modal");
const playAgainBtn = gameModal.querySelector("button");

// Initializing game variables
let currentWord, correctLetters, wrongGuessCount;
const maxGuesses = 6;

const resetGame = () => {
    // Ressetting game variables and UI elements
    correctLetters = [];
    wrongGuessCount = 0;
    hangmanImage.src = "images/hangman-0.svg";
    guessesText.innerText = `${wrongGuessCount} / ${maxGuesses}`;
    wordDisplay.innerHTML = currentWord.split("").map(() => `<li class="letter"></li>`).join("");
    keyboardDiv.querySelectorAll("button").forEach(btn => btn.disabled = false);
    gameModal.classList.remove("show");
}

const getRandomWord = () => {
    // Selecting a random word and hint from the wordList
    const { word, hint } = wordList[Math.floor(Math.random() * wordList.length)];
    currentWord = word; // Making currentWord as random word
    document.querySelector(".hint-text b").innerText = hint;
    resetGame();
}

const gameOver = (isVictory) => {
    // After game complete.. showing modal with relevant details
    const modalText = isVictory ? `You found the word:` : 'The correct word was:';
    gameModal.querySelector("img").src = `images/${isVictory ? 'victory' : 'lost'}.gif`;
    gameModal.querySelector("h4").innerText = isVictory ? 'Congrats!' : 'Game Over!';
    gameModal.querySelector("p").innerHTML = `${modalText} <b>${currentWord}</b>`;
    gameModal.classList.add("show");
}

const initGame = (button, clickedLetter) => {
    // Checking if clickedLetter is exist on the currentWord
    if(currentWord.includes(clickedLetter)) {
        // Showing all correct letters on the word display
        [...currentWord].forEach((letter, index) => {
            if(letter === clickedLetter) {
                correctLetters.push(letter);
                wordDisplay.querySelectorAll("li")[index].innerText = letter;
                wordDisplay.querySelectorAll("li")[index].classList.add("guessed");
            }
        });
    } else {
        // If clicked letter doesn't exist then update the wrongGuessCount and hangman image
        wrongGuessCount++;
        hangmanImage.src = `images/hangman-${wrongGuessCount}.svg`;
    }
    button.disabled = true; // Disabling the clicked button so user can't click again
    guessesText.innerText = `${wrongGuessCount} / ${maxGuesses}`;

    // Calling gameOver function if any of these condition meets
    if(wrongGuessCount === maxGuesses) return gameOver(false);
    if(correctLetters.length === currentWord.length) return gameOver(true);
}

// Creating keyboard buttons and adding event listeners
for (let i = 97; i <= 122; i++) {
    const button = document.createElement("button");
    button.innerText = String.fromCharCode(i);
    keyboardDiv.appendChild(button);
    button.addEventListener("click", (e) => initGame(e.target, String.fromCharCode(i)));
}

getRandomWord();
playAgainBtn.addEventListener("click", getRandomWord);

That’s all! To understand JavaScript code better, I recommend watching the above video tutorial, paying close attention to the code comments, and experimenting with the code.

Conclusion and Final Words

In conclusion, building a Hangman game from scratch using HTML, CSS, and JavaScript is an enjoyable and rewarding experience that can strengthen your web development and problem-solving skills. I believe that by following the steps in this post, you’ve successfully built your very own Hangman game.

Remember to experiment and customize your game to add personal touches and make it even more engaging. To continue improving your skills, I recommend exploring my blog post on How to Build Snake Game in HTML, CSS, and JavaScript.

If you encounter any problems while building your Hangman game, you can download the source code files for this game project for free by clicking the Download button. You can also view a live demo of it by clicking the View Live button.

]]>
https://www.codingnepalweb.com/build-hangman-game-html-javascript/feed/ 0
10 Easy JavaScript Games for Beginners with Source Code https://www.codingnepalweb.com/best-javascript-games-for-beginners/ https://www.codingnepalweb.com/best-javascript-games-for-beginners/#comments Fri, 24 Feb 2023 17:14:49 +0000 https://www.codingnepalweb.com/?p=4028 10 Easy JavaScript Games for Beginners with Source Code

Are you looking for a fun and engaging way to learn JavaScript? Creating games is a great way to learn the language and gain experience with programming concepts such as logic, algorithms, and problem-solving skills.

In this blog post, I will share the 10 Easy to Build JavaScript Games for Beginners. Each game on this list is simple but challenging enough to help you learn new JavaScript concepts. So, whether you’re a beginner or an experienced developer, learning to code games with JavaScript is a rewarding experience.

To make your learning process easier, each game is built with HTML, CSS, and vanilla JavaScript which means no external libraries or frameworks are used. I’ve also provided the source code and a video tutorial for all the games on this list.

You can easily reference these resources for guidance if you encounter any problems. So, let’s not waste more time and dive right into the game list!

1. Memory Card Game

Build A Memory Card Game in HTML CSS & JavaScript

Memory Card is a beginner-friendly game that you can create using HTML, CSS, and JavaScript. In this game, 16 cards are placed randomly on the screen, and each pair of cards has the same image. The objective of the game is to find all the matching pairs by clicking on the cards.

There’s no time limit to finding the matching cards, so players can take their time and focus on improving their memory. Creating this game is a great way to practice different JavaScript concepts, including event listeners, loops, arrays, and others.

2. Typing Speed Test Game

Typing Speed Test Game in HTML CSS & JavaScript

You may have tested your typing speed on different typing speed test websites. In this game, users have 60 seconds to type as many characters as possible and can check their WPM, CPM, accuracy, and more. Users can even erase their incorrect characters or go back using the backspace key.

Creating this game is a good way to improve your problem-solving skills and gain a better understanding of JavaScript concepts such as manipulating the DOM, handling event listeners, and creating user-friendly designs.

3. Hangman Game with Illustration

Hangman is the classic word-guessing game you’ve likely enjoyed playing. In this game, players try to guess all the letters of a randomly generated word within a given number of tries. There is also a hangman illustration that will progressively appear on the gallows for each incorrect guess.

Building a Hangman game from scratch using HTML, CSS, and JavaScript is an enjoyable and rewarding experience that can strengthen your web development and problem-solving skills.

Build A Hangman Game in HTML CSS and JavaScript

4. Quiz Game with Timer

Quiz Game with Timer using JavaScript

Quiz is a very popular game that every beginner tries to create using JavaScript. In this game, the users will be asked multiple questions with options and must choose the correct one within 15 seconds. Ultimately, the user score will be shown based on correct answers only.

Creating a Quiz game can help you understand various JavaScript concepts, including manipulating the DOM, using setInterval, working with arrays of objects, writing functions, and using loops. Moreover, this game project can also provide you with valuable experience in HTML and CSS, which can help you in web development.

5. Word Scramble Game

Word Scramble Game in HTML CSS & JavaScript Word Game in JavaScript

Word scramble is an easy word game you can create as a beginner. In this game, players must unscramble a set of letters to form a word within a given time limit of 30 seconds. And to make the game a little easier, users also get a hint about the word they are trying to guess.

By creating this word game, you can gain hands-on experience with essential JavaScript concepts, including arrays, objects, functions, DOM manipulation, string manipulation, event listeners, and conditional statements.

6. Tic Tac Toe Game

Tic Tac Toe Game in JavaScript

Tic Tac Toe is a well-known game that you can build to improve your JavaScript skills. In this game, the player needs to get three of the same symbol in a row, either horizontally, vertically, or diagonally, to win. The second player in this game is the bot, which plays automatically after each player’s turn.

Creating a Tic Tac Toe game can help you develop critical thinking and problem-solving abilities. You’ll learn many important JavaScript concepts, such as DOM manipulation, conditional statements, functions, arrays, event listeners, and more.

It can be a fun way to learn and apply these fundamental concepts while also improving your understanding of game development.

7. Number Guessing Game

Number Guessing Game HTML CSS JavaScript

Random number guessing is an easy game to create that every beginner must try. This game involves the computer or bot selecting a random number that you have to guess correctly. The game provides hints to help you along the way, and you have ten chances to make the correct guess.

It’s a simple but enjoyable game that can help you learn the basics of JavaScript programming, game logic, CSS styling, and more.

8. Word Guessing Game

Word Guessing Game in HTML CSS & JavaScript

Word guessing is the second-word game on this list that you can create as a beginner. In this game, the user has to guess all the letters of a randomly generated word within a specified number of tries. The game provides hints to help make the guessing process easier.

This word game helps you learn how to use JavaScript concepts like setInterval, DOM manipulation, arrays, objects, etc. to create an engaging and interactive game that keeps users engaged and entertained.

9. Rock Paper Scissors Game

Rock Paper Scissors Game HTML CSS JavaScript

Rock, Paper, Scissors is a game that’s widely enjoyed by beginner developers who want to build a simple game. In this game, you’ll play against a bot or computer, and the rules are straightforward: rock beats scissors, scissors beat paper, and paper beats rock.

It’s an excellent game project to work on if you want to develop your skills while creating an entertaining game. You’ll have fun while learning essential programming concepts that can be applied to other projects in the future.

10. Classic Snake Game

Create A Snake Game in HTML CSS & JavaScript JavaScript Game Tutorial

Snake is a classic arcade game that many of us played as children. But now you can create your own version of the game using JavaScript. In this game, players must guide the snake to eat food that appears randomly on the board. The game will end if the snake hits a wall or its own body.

What makes this game even more exciting is that users can play it on a PC using keyboard arrow keys or on a mobile device using touch-based arrow buttons.

Creating a snake game helps you improve problem-solving skills and logical thinking. You’ll also gain a deep understanding of programming concepts like loops, arrays, conditional statements, DOM manipulation, and game loops.

Conclusion and Final Words

In conclusion, these JavaScript games offer a great opportunity for beginners to improve their coding and problem-solving skills. From a memory card to the snake, these game projects cover various aspects of web and game development, including HTML, CSS, and JavaScript.

Choose a game that interests you and get ready to code. I recommended that you try creating these projects on your own rather than simply copying the source code. So, you’ll gain hands-on experience with essential programming concepts that can help you develop a strong foundation for future projects.

Furthermore, you can check out my Top 10 JavaScript Projects for Beginners to get extra coding projects to learn. Remember, practice is key when it comes to coding, so keep coding and experimenting with new ideas to improve your skills. Happy Coding!

]]>
https://www.codingnepalweb.com/best-javascript-games-for-beginners/feed/ 3
Word Guessing Game in HTML CSS & JavaScript https://www.codingnepalweb.com/word-guessing-game-html-css-javascript/ https://www.codingnepalweb.com/word-guessing-game-html-css-javascript/#comments Wed, 29 Jun 2022 10:29:51 +0000 https://www.codingnepalweb.com/?p=2457 Word Guessing Game in HTML CSS & JavaScript

Hey friends, today in this blog, you’ll learn to build a Word Guessing Game in HTML CSS & JavaScript. This game is similar to the hangman game. I’ve already shared many blogs related to JavaScript games like Memory Card, Typing Speed Test, Quiz, etc. you can view them as well.

The word guessing game is a task that which the player has to find all letters of a random word in the given tries. The game will also give you hints to make your guess easy.

My word guessing game is the same as I said above. You can also see it in the preview image. If you want to see a demo of how this game works or how I created it using HTML CSS & JavaScript, you can watch the given YouTube video.

Video Tutorial of Word Guessing Game in JavaScript

 

 
In the above video, you have seen the demo of this word guessing game and how I built it with vanilla JavaScript. I tried to make the game codes as simple as possible and explained each JavaScript line with written comments.

So, please watch the complete video to understand the codes and concepts behind creating a word guessing game. But, if you liked this game and want to get source codes or files, you can get them from the bottom of this page.

You might like this:

Word Guessing Game in JavaScript [Source Codes]

To create this Word Guessing Game in JavaScript. First, you need to create four Files: HTML, CSS & JavaScript Files. After creating these files just paste the given codes into your file. You can also download the source code files of this Word Guessing from the below download button.

First, create an HTML file with the name index.html and paste the given codes into your HTML file. Remember, you’ve to create a file with a .html extension.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Word Guessing Game JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <div class="wrapper">
      <h1>Guess the Word</h1>
      <div class="content">
        <input type="text" class="typing-input" maxlength="1">
        <div class="inputs"></div>
        <div class="details">
          <p class="hint">Hint: <span></span></p>
          <p class="guess-left">Remaining guesses: <span></span></p>
          <p class="wrong-letter">Wrong letters: <span></span></p>
        </div>
        <button class="reset-btn">Reset Game</button>
      </div>
    </div>

    <script src="js/words.js"></script>
    <script src="js/script.js"></script>

  </body>
</html>

Second, create a CSS file with the name style.css and paste the given codes into your CSS file. Remember, you’ve to create a file with a .css extension.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  padding: 0 10px;
  min-height: 100vh;
  align-items: center;
  justify-content: center;
  background: #1BB295;
}
.wrapper{
  width: 430px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}
.wrapper h1{
  font-size: 25px;
  font-weight: 500;
  padding: 20px 25px;
  border-bottom: 1px solid #ccc;
}
.wrapper .content{
  margin: 25px 25px 35px;
}
.content .inputs{
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
.inputs input{
  height: 57px;
  width: 56px;
  margin: 4px;
  font-size: 24px;
  font-weight: 500;
  color: #1ba98c;
  text-align: center;
  border-radius: 5px;
  background: none;
  pointer-events: none;
  text-transform: uppercase;
  border: 1px solid #B5B5B5;
}
.typing-input {
  opacity: 0;
  z-index: -999;
  position: absolute;
  pointer-events: none;
}
.inputs input:first-child{
  margin-left: 0px;
}
.content .details{
  margin: 20px 0 25px;
}
.details p{
  font-size: 19px;
  margin-bottom: 10px;
}
.content .reset-btn{
  width: 100%;
  border: none;
  cursor: pointer;
  color: #fff;
  outline: none;
  padding: 15px 0;
  font-size: 17px;
  border-radius: 5px;
  background: #1BB295;
  transition: all 0.3s ease;
}
.content .reset-btn:hover{
  background: #18a589;
}

@media screen and (max-width: 460px) {
  .wrapper {
    width: 100%;
  }
  .wrapper h1{
    font-size: 22px;
    padding: 16px 20px;
  }
  .wrapper .content{
    margin: 25px 20px 35px;
  }
  .inputs input{
    height: 51px;
    width: 50px;
    margin: 3px;
    font-size: 22px;
  }
  .details p{
    font-size: 17px;
  }
  .content .reset-btn{
    padding: 14px 0;
    font-size: 16px;
  }
}

Third, create a JavaScript file with the name words.js and paste the given codes into your JavaScript file. Remember, you’ve to create a file with a .js extension and it should be inside the js folder. We’ll store random word details as an object in this file.

const wordList = [
    {
        word: "python",
        hint: "programming language"
    },
    {
        word: "guitar",
        hint: "a musical instrument"
    },
    {
        word: "aim",
        hint: "a purpose or intention"
    },
    {
        word: "venus",
        hint: "planet of our solar system"
    },
    {
        word: "gold",
        hint: "a yellow precious metal"
    },
    {
        word: "ebay",
        hint: "online shopping site"
    },
    {
        word: "golang",
        hint: "programming language"
    },
    {
        word: "coding",
        hint: "related to programming"
    },
    {
        word: "matrix",
        hint: "science fiction movie"
    },
    {
        word: "bugs",
        hint: "related to programming"
    },
    {
        word: "avatar",
        hint: "epic science fiction film"
    },
    {
        word: "gif",
        hint: "a file format for image"
    },
    {
        word: "mental",
        hint: "related to the mind"
    },
    {
        word: "map",
        hint: "diagram represent of an area"
    },
    {
        word: "island",
        hint: "land surrounded by water"
    },
    {
        word: "hockey",
        hint: "a famous outdoor game"
    },
    {
        word: "chess",
        hint: "related to an indoor game"
    },
    {
        word: "viber",
        hint: "a social media app"
    },
    {
        word: "github",
        hint: "code hosting platform"
    },
    {
        word: "png",
        hint: "a image file format"
    },
    {
        word: "silver",
        hint: "precious greyish-white metal"
    },
    {
        word: "mobile",
        hint: "an electronic device"
    },
    {
        word: "gpu",
        hint: "computer component"
    },
    {
        word: "java",
        hint: "programming language"
    },
    {
        word: "google",
        hint: "famous search engine"
    },
    {
        word: "venice",
        hint: "famous city of waters"
    },
    {
        word: "excel",
        hint: "microsoft product for windows"
    },
    {
        word: "mysql",
        hint: "a relational database system"
    },
    {
        word: "nepal",
        hint: "developing country name"
    },
    {
        word: "flute",
        hint: "a musical instrument"
    },
    {
        word: "crypto",
        hint: "related to cryptocurrency"
    },
    {
        word: "tesla",
        hint: "unit of magnetic flux density"
    },
    {
        word: "mars",
        hint: "planet of our solar system"
    },
    {
        word: "proxy",
        hint: "related to server application"
    },
    {
        word: "email",
        hint: "related to exchanging message"
    },
    {
        word: "html",
        hint: "markup language for the web"
    },
    {
        word: "air",
        hint: "related to a gas"
    },
    {
        word: "idea",
        hint: "a thought or suggestion"
    },
    {
        word: "server",
        hint: "related to computer or system"
    },
    {
        word: "svg",
        hint: "a vector image format"
    },
    {
        word: "jpeg",
        hint: "a image file format"
    },
    {
        word: "search",
        hint: "act to find something"
    },
    {
        word: "key",
        hint: "small piece of metal"
    },
    {
        word: "egypt",
        hint: "a country name"
    },
    {
        word: "joker",
        hint: "psychological thriller film"
    },
    {
        word: "dubai",
        hint: "developed country name"
    },
    {
        word: "photo",
        hint: "representation of person or scene"
    },
    {
        word: "nile",
        hint: "largest river in the world"
    },
    {
        word: "rain",
        hint: "related to a water"
    },
]

Last, create a JavaScript file with the name script.js and paste the given codes into your JavaScript file. Remember, you’ve to create a file with a .js extension and it should be inside the js folder.

const inputs = document.querySelector(".inputs"),
hintTag = document.querySelector(".hint span"),
guessLeft = document.querySelector(".guess-left span"),
wrongLetter = document.querySelector(".wrong-letter span"),
resetBtn = document.querySelector(".reset-btn"),
typingInput = document.querySelector(".typing-input");

let word, maxGuesses, incorrectLetters = [], correctLetters = [];

function randomWord() {
    let ranItem = wordList[Math.floor(Math.random() * wordList.length)];
    word = ranItem.word;
    maxGuesses = word.length >= 5 ? 8 : 6;
    correctLetters = []; incorrectLetters = [];
    hintTag.innerText = ranItem.hint;
    guessLeft.innerText = maxGuesses;
    wrongLetter.innerText = incorrectLetters;

    let html = "";
    for (let i = 0; i < word.length; i++) {
        html += `<input type="text" disabled>`;
        inputs.innerHTML = html;
    }
}
randomWord();

function initGame(e) {
    let key = e.target.value.toLowerCase();
    if(key.match(/^[A-Za-z]+$/) && !incorrectLetters.includes(` ${key}`) && !correctLetters.includes(key)) {
        if(word.includes(key)) {
            for (let i = 0; i < word.length; i++) {
                if(word[i] == key) {
                    correctLetters += key;
                    inputs.querySelectorAll("input")[i].value = key;
                }
            }
        } else {
            maxGuesses--;
            incorrectLetters.push(` ${key}`);
        }
        guessLeft.innerText = maxGuesses;
        wrongLetter.innerText = incorrectLetters;
    }
    typingInput.value = "";

    setTimeout(() => {
        if(correctLetters.length === word.length) {
            alert(`Congrats! You found the word ${word.toUpperCase()}`);
            return randomWord();
        } else if(maxGuesses < 1) {
            alert("Game over! You don't have remaining guesses");
            for(let i = 0; i < word.length; i++) {
                inputs.querySelectorAll("input")[i].value = word[i];
            }
        }
    }, 100);
}

resetBtn.addEventListener("click", randomWord);
typingInput.addEventListener("input", initGame);
inputs.addEventListener("click", () => typingInput.focus());
document.addEventListener("keydown", () => typingInput.focus());

That’s all, now you’ve successfully built a Word Guessing Game in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

 

]]>
https://www.codingnepalweb.com/word-guessing-game-html-css-javascript/feed/ 5