JavaScript Games – 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
Build A Playable PIANO in HTML CSS & JavaScript https://www.codingnepalweb.com/playable-piano-html-css-javascript/ https://www.codingnepalweb.com/playable-piano-html-css-javascript/#comments Mon, 12 Dec 2022 01:23:24 +0000 https://www.codingnepalweb.com/?p=3720 Build A Playable PIANO in HTML CSS & JavaScript Piano in JavaScript

Using JavaScript to build a playable piano can be a fun and challenging way to learn and improve your coding skills. This blog will teach you How to Make A Virtual Playable PIANO in HTML, CSS, and JavaScript from scratch that can be played directly in a web browser.

If you don’t know, a piano is a musical instrument that produces sound by striking a series of keys or notes on a keyboard. On my piano, users can play various tunes by clicking on the keys or using the keyboard keys. They can also adjust the volume and show or hide shortcut keys on the piano.

Because of its responsiveness, this piano also works smoothly on touch devices like phones. If you’re excited to view a live demo of this piano, you can click here to view it. For a full video tutorial of this playable piano, please watch the following YouTube video:

Video Tutorial of Playable PIANO in JavaScript

 
I hope you enjoyed the demo of this piano and were able to understand the code and logic behind its creation using HTML, CSS, and JavaScript. This piano is built to help those who are interested in building their own interactive web projects, and I believe this video tutorial has helped with this.

If you haven’t watched the video, you can continue reading this blog to know how to build this piano on your own. Otherwise, you can scroll down to the bottom of the page to copy or download the necessary code for this piano.

Did you know, you can also create a fully functional Music Player using vanilla JavaScript? If not, you can learn how to make it here Create Custom Music Player in JavaScript. Working on this Music Player will give you a solid foundation in HTML, CSS, and JavaScript.

Steps to Build A Playable PIANO in JavaScript

To build a playable virtual piano using HTML, CSS, and JavaScript, follow the given steps line by line:

  1. Create a folder. You can name this folder whatever you want and put the files listed below inside it.
  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 script.js file. The file name must be script and its extension .js
  5. Download the tunes folder of this piano from Google Drive and put it in the same project folder.

First, paste the following codes into your index.html file:

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Playable Piano JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="wrapper">
      <header>
        <h2>Playable PIANO</h2>
        <div class="column volume-slider">
          <span>Volume</span><input type="range" min="0" max="1" value="0.5" step="any">
        </div>
        <div class="column keys-checkbox">
          <span>Show Keys</span><input type="checkbox" checked>
        </div>
      </header>
      <ul class="piano-keys">
        <li class="key white" data-key="a"><span>a</span></li>
        <li class="key black" data-key="w"><span>w</span></li>
        <li class="key white" data-key="s"><span>s</span></li>
        <li class="key black" data-key="e"><span>e</span></li>
        <li class="key white" data-key="d"><span>d</span></li>
        <li class="key white" data-key="f"><span>f</span></li>
        <li class="key black" data-key="t"><span>t</span></li>
        <li class="key white" data-key="g"><span>g</span></li>
        <li class="key black" data-key="y"><span>y</span></li>
        <li class="key white" data-key="h"><span>h</span></li>
        <li class="key black" data-key="u"><span>u</span></li>
        <li class="key white" data-key="j"><span>j</span></li>
        <li class="key white" data-key="k"><span>k</span></li>
        <li class="key black" data-key="o"><span>o</span></li>
        <li class="key white" data-key="l"><span>l</span></li>
        <li class="key black" data-key="p"><span>p</span></li>
        <li class="key white" data-key=";"><span>;</span></li>
      </ul>
    </div>

  </body>
</html>

Second, paste the following codes into your style.css file:

/* 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;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #E3F2FD;
}
.wrapper {
  padding: 35px 40px;
  border-radius: 20px;
  background: #141414;
}
.wrapper header {
  display: flex;
  color: #B2B2B2;
  align-items: center;
  justify-content: space-between;
}
header h2 {
  font-size: 1.6rem;
}
header .column {
  display: flex;
  align-items: center;
}
header span {
  font-weight: 500;
  margin-right: 15px;
  font-size: 1.19rem;
}
header input {
  outline: none;
  border-radius: 30px;
}
.volume-slider input {
  accent-color: #fff;
}
.keys-checkbox input {
  height: 30px;
  width: 60px;
  cursor: pointer;
  appearance: none;
  position: relative;
  background: #4B4B4B
}
.keys-checkbox input::before {
  content: "";
  position: absolute;
  top: 50%;
  left: 5px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #8c8c8c;
  transform: translateY(-50%);
  transition: all 0.3s ease;
}
.keys-checkbox input:checked::before {
  left: 35px;
  background: #fff;
}
.piano-keys {
  display: flex;
  list-style: none;
  margin-top: 40px;
}
.piano-keys .key {
  cursor: pointer;
  user-select: none;
  position: relative;
  text-transform: uppercase;
}
.piano-keys .black {
  z-index: 2;
  width: 44px;
  height: 140px;
  margin: 0 -22px 0 -22px;
  border-radius: 0 0 5px 5px;
  background: linear-gradient(#333, #000);
}
.piano-keys .black.active {
  box-shadow: inset -5px -10px 10px rgba(255,255,255,0.1);
  background:linear-gradient(to bottom, #000, #434343);
}
.piano-keys .white {
  height: 230px;
  width: 70px;
  border-radius: 8px;
  border: 1px solid #000;
  background: linear-gradient(#fff 96%, #eee 4%);
}
.piano-keys .white.active {
  box-shadow: inset -5px 5px 20px rgba(0,0,0,0.2);
  background:linear-gradient(to bottom, #fff 0%, #eee 100%);
}
.piano-keys .key span {
  position: absolute;
  bottom: 20px;
  width: 100%;
  color: #A2A2A2;
  font-size: 1.13rem;
  text-align: center;
}
.piano-keys .key.hide span {
  display: none;
}
.piano-keys .black span {
  bottom: 13px;
  color: #888888;
}

@media screen and (max-width: 815px) {
  .wrapper {
    padding: 25px;
  }
  header {
    flex-direction: column;
  }
  header :where(h2, .column) {
    margin-bottom: 13px;
  }
  .volume-slider input {
    max-width: 100px;
  }
  .piano-keys {
    margin-top: 20px;
  }
  .piano-keys .key:where(:nth-child(9), :nth-child(10)) {
    display: none;
  }
  .piano-keys .black {
    height: 100px;
    width: 40px;
    margin: 0 -20px 0 -20px;
  }
  .piano-keys .white {
    height: 180px;
    width: 60px;
  }
}

@media screen and (max-width: 615px) {
  .piano-keys .key:nth-child(13),
  .piano-keys .key:nth-child(14),
  .piano-keys .key:nth-child(15),
  .piano-keys .key:nth-child(16),
  .piano-keys .key :nth-child(17) {
    display: none;
  }
  .piano-keys .white {
    width: 50px;
  }
}

Last, paste the following codes into your script.js file: I’ve written comments on each JavaScript line so you can easily understand which line does what. But to better understand them, I recommended you watch the above video tutorial.

const pianoKeys = document.querySelectorAll(".piano-keys .key"),
volumeSlider = document.querySelector(".volume-slider input"),
keysCheckbox = document.querySelector(".keys-checkbox input");

let allKeys = [],
audio = new Audio(`tunes/a.wav`); // by default, audio src is "a" tune

const playTune = (key) => {
    audio.src = `tunes/${key}.wav`; // passing audio src based on key pressed 
    audio.play(); // playing audio

    const clickedKey = document.querySelector(`[data-key="${key}"]`); // getting clicked key element
    clickedKey.classList.add("active"); // adding active class to the clicked key element
    setTimeout(() => { // removing active class after 150 ms from the clicked key element
        clickedKey.classList.remove("active");
    }, 150);
}

pianoKeys.forEach(key => {
    allKeys.push(key.dataset.key); // adding data-key value to the allKeys array
    // calling playTune function with passing data-key value as an argument
    key.addEventListener("click", () => playTune(key.dataset.key));
});

const handleVolume = (e) => {
    audio.volume = e.target.value; // passing the range slider value as an audio volume
}

const showHideKeys = () => {
    // toggling hide class from each key on the checkbox click
    pianoKeys.forEach(key => key.classList.toggle("hide"));
}

const pressedKey = (e) => {
    // if the pressed key is in the allKeys array, only call the playTune function
    if(allKeys.includes(e.key)) playTune(e.key);
}

keysCheckbox.addEventListener("click", showHideKeys);
volumeSlider.addEventListener("input", handleVolume);
document.addEventListener("keydown", pressedKey);

That’s all; now you’ve successfully Build A Playable PIANO in HTML, CSS, and JavaScript. If you encounter any problems or your code is not working as expected, you can download the source code files for this PIANO by clicking on the given download button. It’s free, and a zip file will be downloaded that contains the project folder with source code files.

 

]]>
https://www.codingnepalweb.com/playable-piano-html-css-javascript/feed/ 2
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
Build A Memory Card Game in HTML CSS & JavaScript https://www.codingnepalweb.com/build-memory-card-game-html-javascript/ https://www.codingnepalweb.com/build-memory-card-game-html-javascript/#comments Sun, 30 Jan 2022 11:44:07 +0000 https://www.codingnepalweb.com/?p=2348 Build A Memory Card Game in HTML CSS & JavaScript

Hello friends, today in this blog, you’ll learn how to Build A Memory Card Game in HTML CSS & JavaScript. In the earlier blog, I have shared how to build a Typing Speed Test Game in JavaScript, and now it’s time to create a memory or matching cards game.

Memory card is a simple matching cards game in which all the cards are flipped backside on a surface, and two cards are flipped face up over each turn. The objective of this game is to match all the pairs of cards.

In this game (Memory Card Game in JavaScript), You’ll see the two demos. In demo 1, there are 16 cards where every two cards have the same images, but each card is placed randomly, and you have to find them. There is no time limit to find the pairs of cards.

In demo 2, everything is the same as in demo 1, but there is a time limit of 30 seconds, and you have to find the pair of cards in this given time. If you’re feeling difficult to understand what I’m saying, you can watch demos or a full video tutorial of this game.

Video Tutorial of Memory Card Game in JavaScript

 
I hope you have seen the above video, where I have shown the demos of this memory card game and how I created it using HTML CSS & JavaScript. If you’re too beginner and didn’t build any JavaScript project before, then you may have difficulties to understand the codes of this game.

So, I would suggest you watch the video 2-3 times and try to understand each JavaScript line of this game because I have explained the JavaScript codes with written comments which help you to understand the codes more easily but if you liked these matching cards game and want to get source codes or files, you can get them from the bottom of this page.

You might like this:

Memory Card Game in JavaScript [Source Codes]

To create this Memory or Matching Card Game in JavaScript. First, you need to create three Files: HTML, CSS & JavaScript File. After creating these files, you have to paste the given codes into your file.

Remember, If you copy-paste the codes, then you won’t get images that are used in this game, and also you won’t get source codes of demo 2 of this game. If you want these, you can easily download the source files of this memory card game from the bottom download button.

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

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">  
    <title>Memory Card Game in 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">
      <ul class="cards">
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-1.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-6.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-3.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-2.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-1.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-5.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-2.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-6.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-3.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-4.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-5.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-4.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-4.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-4.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-4.png" alt="card-img">
          </div>
        </li>
        <li class="card">
          <div class="view front-view">
            <img src="images/que_icon.svg" alt="icon">
          </div>
          <div class="view back-view">
            <img src="images/img-4.png" alt="card-img">
          </div>
        </li>
      </ul>
    </div>

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

  </body>
</html>

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

/* Import Google Font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #6563FF;
}
.wrapper{
  padding: 25px;
  border-radius: 10px;
  background: #F8F8F8;
  box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}
.cards, .card, .view{
  display: flex;
  align-items: center;
  justify-content: center;
}
.cards{
  height: 400px;
  width: 400px;
  flex-wrap: wrap;
  justify-content: space-between;
}
.cards .card{
  cursor: pointer;
  list-style: none;
  user-select: none;
  position: relative;
  perspective: 1000px;
  transform-style: preserve-3d;
  height: calc(100% / 4 - 10px);
  width: calc(100% / 4 - 10px);
}
.card.shake{
  animation: shake 0.35s ease-in-out;
}
@keyframes shake {
  0%, 100%{
    transform: translateX(0);
  }
  20%{
    transform: translateX(-13px);
  }
  40%{
    transform: translateX(13px);
  }
  60%{
    transform: translateX(-8px);
  }
  80%{
    transform: translateX(8px);
  }
}
.card .view{
  width: 100%;
  height: 100%;
  position: absolute;
  border-radius: 7px;
  background: #fff;
  pointer-events: none;
  backface-visibility: hidden;
  box-shadow: 0 3px 10px rgba(0,0,0,0.1);
  transition: transform 0.25s linear;
}
.card .front-view img{
  width: 19px;
}
.card .back-view img{
  max-width: 45px;
}
.card .back-view{
  transform: rotateY(-180deg);
}
.card.flip .back-view{
  transform: rotateY(0);
}
.card.flip .front-view{
  transform: rotateY(180deg);
}

@media screen and (max-width: 700px) {
  .cards{
    height: 350px;
    width: 350px;
  }
  .card .front-view img{
    width: 17px;
  }
  .card .back-view img{
    max-width: 40px;
  }
}

@media screen and (max-width: 530px) {
  .cards{
    height: 300px;
    width: 300px;
  }
  .card .front-view img{
    width: 15px;
  }
  .card .back-view img{
    max-width: 35px;
  }
}

Last, create a JavaScript file with the name of script.js and paste the given codes in your JavaScript file. Remember, you’ve to create a file with .js extension.

const cards = document.querySelectorAll(".card");

let matched = 0;
let cardOne, cardTwo;
let disableDeck = false;

function flipCard({target: clickedCard}) {
    if(cardOne !== clickedCard && !disableDeck) {
        clickedCard.classList.add("flip");
        if(!cardOne) {
            return cardOne = clickedCard;
        }
        cardTwo = clickedCard;
        disableDeck = true;
        let cardOneImg = cardOne.querySelector(".back-view img").src,
        cardTwoImg = cardTwo.querySelector(".back-view img").src;
        matchCards(cardOneImg, cardTwoImg);
    }
}

function matchCards(img1, img2) {
    if(img1 === img2) {
        matched++;
        if(matched == 8) {
            setTimeout(() => {
                return shuffleCard();
            }, 1000);
        }
        cardOne.removeEventListener("click", flipCard);
        cardTwo.removeEventListener("click", flipCard);
        cardOne = cardTwo = "";
        return disableDeck = false;
    }
    setTimeout(() => {
        cardOne.classList.add("shake");
        cardTwo.classList.add("shake");
    }, 400);

    setTimeout(() => {
        cardOne.classList.remove("shake", "flip");
        cardTwo.classList.remove("shake", "flip");
        cardOne = cardTwo = "";
        disableDeck = false;
    }, 1200);
}

function shuffleCard() {
    matched = 0;
    disableDeck = false;
    cardOne = cardTwo = "";
    let arr = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8];
    arr.sort(() => Math.random() > 0.5 ? 1 : -1);
    cards.forEach((card, i) => {
        card.classList.remove("flip");
        let imgTag = card.querySelector(".back-view img");
        imgTag.src = `images/img-${arr[i]}.png`;
        card.addEventListener("click", flipCard);
    });
}

shuffleCard();
    
cards.forEach(card => {
    card.addEventListener("click", flipCard);
});

That’s all, now you’ve successfully built a Memory Card Game in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problem, 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. After you extracted this zip file, you’ll get two folders of both demo 1 and demo 2 of this game.

 

]]>
https://www.codingnepalweb.com/build-memory-card-game-html-javascript/feed/ 11
Typing Speed Test Game in HTML CSS & JavaScript https://www.codingnepalweb.com/typing-speed-test-game-html-javascript/ https://www.codingnepalweb.com/typing-speed-test-game-html-javascript/#comments Sun, 02 Jan 2022 10:09:50 +0000 https://www.codingnepalweb.com/?p=2330 Typing Speed Test Game in HTML CSS & JavaScript

Hey friends, today in this blog, I’ll show you how to build a Typing Speed Test Game in HTML CSS & JavaScript. In the earlier blog, I have shared how to build a Dictionary App using JavaScript, and now it’s time to create a Typing Speed Test Game.

Typing speed test is a game where you can check your typing speed like WPM (Word Per Minute), CPM (Character Per Minute), Accuracy, etc. In my Typing Speed Test Game, the max time for typing is 60 seconds. Once you start typing, you’ll see your time, mistakes, WPM, and CPM at the bottom.

You can also erase your incorrect characters or go backward by pressing the backspace key of your keyboard. Once you have typed all characters or the time is completed, you can click on the try again button to reset the result and load a new paragraph.

Video Tutorial of Typing Speed Test Game in JavaScript

 
In the above video, you have seen the demo of this Typing Speed Test Game and how I built this game using HTML CSS & Vanilla JavaScript. I hope you liked this typing speed game and understood the basic codes behind creating this game.

If you’re already familiar with JavaScript and have built projects in it then you might easily understand the codes of this game but if you are too beginner at this and didn’t build a project before then you may have difficulties to understanding the codes and concepts of this Typing Speed Test Game.

If you liked this game (Typing Speed Test Game) and want to get source codes or files, you can get it from the bottom of this page. I want to suggest that beginners watch the video above rather than downloading the coding files because, in the video, I have explained each JavaScript line with written comments which helps you to understand the particular JavaScript line more easily.

You might like this:

Typing Speed Test Game in JavaScript [Source Codes]

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

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

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">  
    <title>Typing Speed Test Game | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <div class="wrapper">
      <input type="text" class="input-field">
      <div class="content-box">
        <div class="typing-text">
          <p></p>
        </div>
        <div class="content">
          <ul class="result-details">
            <li class="time">
              <p>Time Left:</p>
              <span><b>60</b>s</span>
            </li>
            <li class="mistake">
              <p>Mistakes:</p>
              <span>0</span>
            </li>
            <li class="wpm">
              <p>WPM:</p>
              <span>0</span>
            </li>
            <li class="cpm">
              <p>CPM:</p>
              <span>0</span>
            </li>
          </ul>
          <button>Try Again</button>
        </div>
      </div>
    </div>

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

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

/* Import Google Font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  padding: 0 10px;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #17A2B8;
}
::selection{
  color: #fff;
  background: #17A2B8;
}
.wrapper{
  width: 770px;
  padding: 35px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 10px 15px rgba(0,0,0,0.05);
}
.wrapper .input-field{
  opacity: 0;
  z-index: -999;
  position: absolute;
}
.wrapper .content-box{
  padding: 13px 20px 0;
  border-radius: 10px;
  border: 1px solid #bfbfbf;
}
.content-box .typing-text{
  overflow: hidden;
  max-height: 256px;
}
.typing-text::-webkit-scrollbar{
  width: 0;
}
.typing-text p{
  font-size: 21px;
  text-align: justify;
  letter-spacing: 1px;
  word-break: break-all;
}
.typing-text p span{
  position: relative;
}
.typing-text p span.correct{
  color: #56964f;
}
.typing-text p span.incorrect{
  color: #cb3439;
  outline: 1px solid #fff;
  background: #ffc0cb;
  border-radius: 4px;
}
.typing-text p span.active{
  color: #17A2B8;
}
.typing-text p span.active::before{
  position: absolute;
  content: "";
  height: 2px;
  width: 100%;
  bottom: 0;
  left: 0;
  opacity: 0;
  border-radius: 5px;
  background: #17A2B8;
  animation: blink 1s ease-in-out infinite;
}
@keyframes blink{
  50%{ 
    opacity: 1; 
  }
}
.content-box .content{
  margin-top: 17px;
  display: flex;
  padding: 12px 0;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  border-top: 1px solid #bfbfbf;
}
.content button{
  outline: none;
  border: none;
  width: 105px;
  color: #fff;
  padding: 8px 0;
  font-size: 16px;
  cursor: pointer;
  border-radius: 5px;
  background: #17A2B8;
  transition: transform 0.3s ease;
}
.content button:active{
  transform: scale(0.97);
}
.content .result-details{
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: calc(100% - 140px);
  justify-content: space-between;
}
.result-details li{
  display: flex;
  height: 20px;
  list-style: none;
  position: relative;
  align-items: center;
}
.result-details li:not(:first-child){
  padding-left: 22px;
  border-left: 1px solid #bfbfbf;
}
.result-details li p{
  font-size: 19px;
}
.result-details li span{
  display: block;
  font-size: 20px;
  margin-left: 10px;
}
li span b{
  font-weight: 500;
}
li:not(:first-child) span{
  font-weight: 500;
}
@media (max-width: 745px) {
  .wrapper{
    padding: 20px;
  }
  .content-box .content{
    padding: 20px 0;
  }
  .content-box .typing-text{
    max-height: 100%;
  }
  .typing-text p{
    font-size: 19px;
    text-align: left;
  }
  .content button{
    width: 100%;
    font-size: 15px;
    padding: 10px 0;
    margin-top: 20px;
  }
  .content .result-details{
    width: 100%;
  }
  .result-details li:not(:first-child){
    border-left: 0;
    padding: 0;
  }
  .result-details li p, 
  .result-details li span{
    font-size: 17px;
  }
}
@media (max-width: 518px) {
  .wrapper .content-box{
    padding: 10px 15px 0;
  }
  .typing-text p{
    font-size: 18px;
  }
  .result-details li{
    margin-bottom: 10px;
  }
  .content button{
    margin-top: 10px;
  }
}

Third, create a folder with the js name and then create two javascript files (paragraphs.js, script.js) files inside this folder. Paste the given codes inside the paragraphs.js file. These are the paragraphs that are shown randomly as typing text. You can add more paragraphs in the array to show more paragraphs on the typing game.

const paragraphs = [
    "Authors often misinterpret the lettuce as a folklore rabbi, when in actuality it feels more like an uncursed bacon. Pursued distances show us how mother-in-laws can be charleses. Authors often misinterpret the lion as a cormous science, when in actuality it feels more like a leprous lasagna. Recent controversy aside, their band was, in this moment, a racemed suit. The clutch of a joke becomes a togaed chair. The first pickled chess is.",
    "In modern times the first scrawny kitten is, in its own way, an input. An ostrich is the beginner of a roast. An appressed exhaust is a gun of the mind. A recorder is a grade from the right perspective. A hygienic is the cowbell of a skin. Few can name a dun brazil that isn't a highbrow playroom. The unwished beast comes from a thorny oxygen. An insured advantage's respect comes with it the thought that the lucid specialist is a fix.",
    "In ancient times the legs could be said to resemble stroppy vegetables. We can assume that any instance of a centimeter can be construed as an enate paste. One cannot separate pairs from astute managers. Those americas are nothing more than fish. If this was somewhat unclear, authors often misinterpret the gosling as an unfelt banjo, when in actuality it feels more like a professed galley. A bow of the squirrel is assumed.",
    "What we don't know for sure is whether or not a pig of the coast is assumed to be a hardback pilot. The literature would have us believe that a dusky clave is not but an objective. Few can name a limbate leo that isn't a sunlit silver. The bow is a mitten. However, the drawer is a bay. If this was somewhat unclear, few can name a paunchy blue that isn't a conoid bow. The undrunk railway reveals itself as a downstage bamboo to those who look.",
    "Their politician was, in this moment, a notour paperback. The first armless grouse is, in its own way, a gear. The coat is a wash. However, a cake is the llama of a caravan. Snakelike armies show us how playgrounds can be viscoses. Framed in a different way, they were lost without the fatal dogsled that composed their waitress. Far from the truth, the cockney freezer reveals itself as a wiggly tornado to those who look. The first hawklike sack.",
    "An aunt is a bassoon from the right perspective. As far as we can estimate, some posit the melic myanmar to be less than kutcha. One cannot separate foods from blowzy bows. The scampish closet reveals itself as a sclerous llama to those who look. A hip is the skirt of a peak. Some hempy laundries are thought of simply as orchids. A gum is a trumpet from the right perspective. A freebie flight is a wrench of the mind. Some posit the croupy.",
    "A baby is a shingle from the right perspective. Before defenses, collars were only operations. Bails are gleesome relatives. An alloy is a streetcar's debt. A fighter of the scarecrow is assumed to be a leisured laundry. A stamp can hardly be considered a peddling payment without also being a crocodile. A skill is a meteorology's fan. Their scent was, in this moment, a hidden feeling. The competitor of a bacon becomes a boxlike cougar.",
    "A broadband jam is a network of the mind. One cannot separate chickens from glowing periods. A production is a faucet from the right perspective. The lines could be said to resemble zincoid females. A deborah is a tractor's whale. Cod are elite japans. Some posit the wiglike norwegian to be less than plashy. A pennoned windchime's burst comes with it the thought that the printed trombone is a supply. Relations are restless tests.",
    "In recent years, some teeming herons are thought of simply as numbers. Nowhere is it disputed that an unlaid fur is a marble of the mind. Far from the truth, few can name a glossy lier that isn't an ingrate bone. The chicken is a giraffe. They were lost without the abscessed leek that composed their fowl. An interviewer is a tussal bomb. Vanward maracas show us how scarfs can be doubts. Few can name an unguled punch that isn't pig.",
    "A cough is a talk from the right perspective. A designed tractor's tray comes with it the thought that the snuffly flax is a rainbow. Their health was, in this moment, an earthy passbook. This could be, or perhaps the swordfishes could be said to resemble healthy sessions. A capricorn is a helium from the right perspective. However, a sled is a mailman's tennis. The competitor of an alarm becomes a toeless raincoat. Their twist was, in this moment.",
    "Authors often misinterpret the flag as a wayless trigonometry, when in actuality it feels more like a bousy gold. Few can name a jasp oven that isn't a stutter grape. They were lost without the huffy religion that composed their booklet. Those waves are nothing more than pedestrians. Few can name a quartered semicolon that isn't a rounding scooter. Though we assume the latter, the literature would have us believe.",
    "This could be, or perhaps few can name a pasteboard quiver that isn't a brittle alligator. A swordfish is a death's numeric. Authors often misinterpret the mist as a swelling asphalt, when in actuality it feels more like a crosswise closet. Some posit the tonal brother-in-law to be less than newborn. We know that the sizes could be said to resemble sleepwalk cycles. Before seasons, supplies were only fighters. Their stew was, in this moment.",
    "The vision of an attempt becomes a lawny output. Dibbles are mis womens. The olden penalty reveals itself as a bustled field to those who look. Few can name a chalky force that isn't a primate literature. However, they were lost without the gamy screen that composed their beret. Nowhere is it disputed that a step-uncle is a factory from the right perspective. One cannot separate paints from dreary windows. What we don't know for sure is whether.",
    "A tramp is a siamese from the right perspective. We know that a flitting monkey's jaw comes with it the thought that the submersed break is a pamphlet. Their cream was, in this moment, a seedy daffodil. The nest is a visitor. Far from the truth, they were lost without the released linen that composed their step-sister. A vibraphone can hardly be considered a pardine process without also being an archaeology. The bay of a hyacinth becomes.",
    "The frosts could be said to resemble backstage chards. One cannot separate colleges from pinkish bacons. Far from the truth, the mom of a rooster becomes a chordal hydrogen. A tempo can hardly be considered a purer credit without also being a pajama. The first combined ease is, in its own way, a pantyhose. Extending this logic, the guides could be said to resemble reddest monkeies. Framed in a different way, an addle hemp is a van.",
    "Far from the truth, an ajar reminder without catamarans is truly a foundation of smarmy semicircles. An alike board without harps is truly a satin of fated pans. A hubcap sees a parent as a painful beautician. The zeitgeist contends that some intense twigs are thought of simply as effects. A cross is a poppied tune. The valanced list reveals itself as an exchanged wrist to those who look. Recent controversy aside.",
    "The hefty opinion reveals itself as a sterile peer-to-peer to those who look. This could be, or perhaps the watch of a diamond becomes a bosom baboon. In recent years, some posit the unstuffed road to be less than altern. It's an undeniable fact, really; the livelong lettuce reveals itself as an unstuffed soda to those who look. In ancient times a bit is a balance's season. The popcorn of a morning becomes a moonless beauty.",
    "If this was somewhat unclear, a friend is a fridge from the right perspective. An upset carriage is a stitch of the mind. To be more specific, a temper is a pair from the right perspective. Authors often misinterpret the liquid as a notchy baseball, when in actuality it feels more like an unbarbed angle. Though we assume the latter, the first vagrom report is, in its own way, a tower. We know that the octopus of a cd becomes an unrent dahlia.",
    "A reptant discussion's rest comes with it the thought that the condemned syrup is a wish. The drake of a wallaby becomes a sonant harp. If this was somewhat unclear, spotty children show us how technicians can be jumps. Their honey was, in this moment, an intime direction. A ship is the lion of a hate. They were lost without the croupous jeep that composed their lily. In modern times a butcher of the birth is assumed to be a spiral bean.",
    "Those cowbells are nothing more than elements. This could be, or perhaps before stockings, thoughts were only opinions. A coil of the exclamation is assumed to be a hurtless toy. A board is the cast of a religion. In ancient times the first stinko sailboat is, in its own way, an exchange. Few can name a tutti channel that isn't a footless operation. Extending this logic, an oatmeal is the rooster of a shake. Those step-sons are nothing more than matches."
];

Last, paste the given codes inside the script.js file and this is the main JavaScript code of this typing speed test game. If you want to increase or decrease the timer of this game then change the value of maxTime variable of this file.

const typingText = document.querySelector(".typing-text p"),
inpField = document.querySelector(".wrapper .input-field"),
tryAgainBtn = document.querySelector(".content button"),
timeTag = document.querySelector(".time span b"),
mistakeTag = document.querySelector(".mistake span"),
wpmTag = document.querySelector(".wpm span"),
cpmTag = document.querySelector(".cpm span");

let timer,
maxTime = 60,
timeLeft = maxTime,
charIndex = mistakes = isTyping = 0;

function loadParagraph() {
    const ranIndex = Math.floor(Math.random() * paragraphs.length);
    typingText.innerHTML = "";
    paragraphs[ranIndex].split("").forEach(char => {
        let span = `<span>${char}</span>`
        typingText.innerHTML += span;
    });
    typingText.querySelectorAll("span")[0].classList.add("active");
    document.addEventListener("keydown", () => inpField.focus());
    typingText.addEventListener("click", () => inpField.focus());
}

function initTyping() {
    let characters = typingText.querySelectorAll("span");
    let typedChar = inpField.value.split("")[charIndex];
    if(charIndex < characters.length - 1 && timeLeft > 0) {
        if(!isTyping) {
            timer = setInterval(initTimer, 1000);
            isTyping = true;
        }
        if(typedChar == null) {
            if(charIndex > 0) {
                charIndex--;
                if(characters[charIndex].classList.contains("incorrect")) {
                    mistakes--;
                }
                characters[charIndex].classList.remove("correct", "incorrect");
            }
        } else {
            if(characters[charIndex].innerText == typedChar) {
                characters[charIndex].classList.add("correct");
            } else {
                mistakes++;
                characters[charIndex].classList.add("incorrect");
            }
            charIndex++;
        }
        characters.forEach(span => span.classList.remove("active"));
        characters[charIndex].classList.add("active");

        let wpm = Math.round(((charIndex - mistakes)  / 5) / (maxTime - timeLeft) * 60);
        wpm = wpm < 0 || !wpm || wpm === Infinity ? 0 : wpm;
        
        wpmTag.innerText = wpm;
        mistakeTag.innerText = mistakes;
        cpmTag.innerText = charIndex - mistakes;
    } else {
        clearInterval(timer);
        inpField.value = "";
    }   
}

function initTimer() {
    if(timeLeft > 0) {
        timeLeft--;
        timeTag.innerText = timeLeft;
        let wpm = Math.round(((charIndex - mistakes)  / 5) / (maxTime - timeLeft) * 60);
        wpmTag.innerText = wpm;
    } else {
        clearInterval(timer);
    }
}

function resetGame() {
    loadParagraph();
    clearInterval(timer);
    timeLeft = maxTime;
    charIndex = mistakes = isTyping = 0;
    inpField.value = "";
    timeTag.innerText = timeLeft;
    wpmTag.innerText = 0;
    mistakeTag.innerText = 0;
    cpmTag.innerText = 0;
}

loadParagraph();
inpField.addEventListener("input", initTyping);
tryAgainBtn.addEventListener("click", resetGame);

That’s all, now you’ve successfully built a Typing Speed Test Game in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problem, 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/typing-speed-test-game-html-javascript/feed/ 6