word guessing game html css and javascript

Word Guessing Game Html, Css And, Javascript (Source Code)

Word Guessing Game Html, Css And, Javascript (Source Code)

Hey Guys, Welcome To The Blog, In This Blog We Are Going To See How To Create An Word Guessing Game Using Html, Css, And Javascript. Before That We Will See About The Project.

The Word Guessing Game Is A Task In Which The Player Has To Find All Letters Of A Random Word From The Given Tries And The Game Will Also Give You Hints That Make Your Guess Easy.

This Project Exact Has The Information Said Above. So Let’s Begin With Creating Our Project By Adding The Respective Source Codes. For That, We First Start With Html Code.

Word Guessing Game Html Code:

<html>

    <head>
        <link rel="stylesheet" href="style.css">
        <script src="script.js"></script>
    </head>

    <body>

        <div id="chooseDifficulty" style="display: block">

            <h1>Guess a Word</h1>
            <h5>Choose a difficulty</h5>
            <button title="very easy" onclick="chooseDif1()">easy</button>
            <button title="not difficult" onclick="chooseDif2()">normal</button>
            <button title="a challenge" onclick="chooseDif3()">hard</button>

        </div>

        <!--not active yet :(-->
        <!--<div id="chooseTheme" style="display: none">

            <h1>Guess a Word</h1>
            <h5>Choose a Theme</h5>
            <button onclick="chooseTheme1()">random</button>
            <button onclick="chooseTheme2()">2</button>
            <button onclick="chooseTheme3()">3</button>

        </div>-->

        <div id="startButton" style="display: none">

            <h1>Guess a Word</h1>
            <button onclick="start()">Start</button>
            <p>Note: Some words may contain a hyphen(-) ex: X-ray</p>

        </div>

        <div id="mainGame" style="display: none">

        <p id="question"></p>

        <input type="text" id="guess" maxlength="1">

        <div>
            <button onclick="enterGuess()">Enter Guess</button>
        </div>

        </div>

        <div id="RRguess" style="display: block">

        <p id="rightGuess"></p>
        <p id ="wrongGuess"></p>
        <p id ="guessesLeft"></p>

        </div>

        <div id="youLose" style="display: none">

            <h1>You Lose</h1>

            <div>
                <button onclick="restart()">Play again?</button>
            </div>

            <p id="correctWordWas"></p>

        </div>

        <div id="youWin" style="display: none">

            <h2>You Win</h2>

            <div>
                <button onclick="restart()">Play again?</button>
            </div>

        </div>

    </body>

</html>

Hey there, we have successfully added our html code. First, we have to create an html file with the name index.Html and paste the code given above. Make sure to save the file with the .Html extension.

100+ Front-end Projects for Web developers (Source Code)

Now in this code, we first linked our css and javascript file with the link mentioned in the head tag. Then we added the div tag with the respective contents inside below. The respective contents inside div tag is given below.

<div id="chooseDifficulty" style="display: block">

            <h1>Guess a Word</h1>
            <h5>Choose a difficulty</h5>
            <button title="very easy" onclick="chooseDif1()">easy</button>
            <button title="not difficult" onclick="chooseDif2()">normal</button>
            <button title="a challenge" onclick="chooseDif3()">hard</button>

        </div>

After this, we are adding the contents after we click start, for that first, we placed it with a div tag with the class name and the contents wee inside it.

Now, in this code, we give separate div tags for every element to perform different operations on different elements. The contents for the project were inside of div tags which are given below.

<div id="startButton" style="display: none">

            <h1>Guess a Word</h1>
            <button onclick="start()">Start</button>
            <p>Note: Some words may contain a hyphen(-) ex: X-ray</p>

        </div>

        <div id="mainGame" style="display: none">

        <p id="question"></p>

        <input type="text" id="guess" maxlength="1">

        <div>
            <button onclick="enterGuess()">Enter Guess</button>
        </div>

        </div>

        <div id="RRguess" style="display: block">

        <p id="rightGuess"></p>
        <p id ="wrongGuess"></p>
        <p id ="guessesLeft"></p>

        </div>

        <div id="youLose" style="display: none">

            <h1>You Lose</h1>

            <div>
                <button onclick="restart()">Play again?</button>
            </div>

            <p id="correctWordWas"></p>

        </div>

        <div id="youWin" style="display: none">

            <h2>You Win</h2>

            <div>
                <button onclick="restart()">Play again?</button>
            </div>

        </div>

Now we have completed our html code successfully. It’s time to move on for css part to style our project so, the respective styling parts css in given below.

Word guessing game css code:

body {
  background-image: url("http://dailyroabox.com/wp-content/uploads/2016/11/Lined-Paper-Template-Google-Docs.jpg");
  background-size: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%)translateY(-50%);
  text-align: center;
}

Now the respective css code has been added successfully. In this code there is more advantage has it contains only few lines of code in which understanding it is easy and efficient.

Simply, first, we start by adding body and inside body section, we fix the background image to the respective image we need and the size of background fixed to 100% which means whole web page, for the contents to relate we are using the position property and lastly we align the contents by alignment properties with the text align center and some animations to perform on the required content.

That’s for css, now we move on to adding the javascript code for further matching the guessed letters with user entered letters.

Word guessing javascript code:

var word = "";
var wordGuess = [];
var wrongGuess = [];
var guessBomb = 0;
var winCount = 1;
var guess = "";
var dif = 0;

function chooseDif1() {
    dif = 1;
    document.getElementById('startButton').style.display='block';
    document.getElementById('chooseDifficulty').style.display='none';
}

function chooseDif2() {
    dif = 2;
    document.getElementById('startButton').style.display='block';
    document.getElementById('chooseDifficulty').style.display='none';
}

function chooseDif3() {
    dif = 3;
    document.getElementById('startButton').style.display='block';
    document.getElementById('chooseDifficulty').style.display='none';
}


function wordw() {
    var randomWords = ["humor", "miniature", "amusing", "creepy", "fact", "risk", "verse", "land", "lumpy", "holiday", "glorious", "weigh", "brake", "pretty", "grin", "capricious", "bite-sized", "misty", "ignore", "certain", "sloppy", "dress", "true", "zonked", "observation", "action", "various", "want", "direful", "suck", "dress", "scarecrow", "judge", "madly", "quizzical", "consist", "fierce", "love", "arrest", "serve", "fit", "hug", "tan", "curve", "eatable", "tub", "race", "innocent", "open", "preach", "steady", "acoustics", "lock", "field", "arrange", "rifle", "learned", "toe", "flow", "competition", "ill-fated", "oatmeal", "match", "male", "measure", "loaf", "smile", "wrestle", "dull", "food", "locket", "bell", "beg", "strengthen", "responsible", "enchanting", "loutish", "switch", "idea", "nine", "squeamish", "pig", "bat", "dear", "trains", "owe", "frogs", "assorted", "lonely", "hurry", "natural", "sun", "snow", "obnoxious", "broken", "friend", "bright", "cake", "sour", "permit", "economic", "lovely", "quick", "van", "tempt", "apparel", "decay", "business", "adjustment", "blushing", "makeshift", "slippery", "load", "winter", "exist", "tongue", "country", "roll", "fast", "moor", "possess", "pat", "pass", "books", "impartial", "hospitable", "dust", "naughty", "extra-large", "tacky", "produce", "committee", "fuzzy", "judicious", "nebulous", "stick", "ear", "copy", "friendly", "press", "distinct", "vegetable", "upset", "venomous", "statement", "sulky", "spell", "x-ray", "square", "taste", "great", "thumb", "adjoining", "chilly", "test", "ancient", "green", "badge", "work", "repeat", "free", "elderly", "doctor", "difficult", "grubby", "approval", "turn", "vivacious", "thundering", "cherries", "rest", "plan", "crime", "sticks", "wealthy", "phone", "suspend", "gullible", "fence", "note", "wall", "interest", "coil", "jump", "enchanted", "funny", "racial", "greasy", "polish", "elbow", "smart", "bore", "crowd", "glistening", "oval", "eggs", "nauseating", "detailed", "veil", "coal"]
    var raNum = Math.floor(Math.random() * 70);
    return randomWords[raNum]
    }


function wordStart() {
    var wordLength = word.length;
    var wordL_ = "";
    var count = wordLength;

    while(count > 0) {
        wordGuess.push(" _ ");
        count -= 1;
    }
}

function winCountFunc() {
    var num = 0;
    var lettUsed = "";
    var count = word.length;

    while(count > 0) {
        if(lettUsed.includes(word[count - 1])) {

        }

        else{
            num += 1;
            lettUsed += word[count - 1];
        }

        count -= 1;
    }

    return num;
}

function start() {
    word = wordw();
    winCount = winCountFunc();

    if(dif == 1) {
        guessBomb = word.length + 5;
    }

    else if(dif == 2) {
        guessBomb = word.length;
    }

    else if(dif == 3) {
        if(word.length % 2 == 0) {
           guessBomb = word.length / 2;
        }
      
        else {
           guessBomb = (word.length - 1) / 2;
        }
    }

    console.log(word);
    document.getElementById('mainGame').style.display='block';
    document.getElementById('startButton').style.display='none';

    document.getElementById("question").innerHTML = "Enter your first guess";

    wordStart();

    document.getElementById('RRguess').style.display='block';
    document.getElementById("rightGuess").innerHTML = "word progress: " + wordGuess;
    document.getElementById("wrongGuess").innerHTML = "Wrong guesses: " + wrongGuess;
    document.getElementById("guessesLeft").innerHTML = "Guesses remaining: " + guessBomb;

    var x = document.getElementById("guess").maxLength;
    //document.getElementById("demo").innerHTML = x;
}

function enterGuess() {
    var lett = document.getElementById("guess").value;
    document.getElementById("guess").value = "";

    if (lett.length === 1){
        var rightOnot = isRightOnot(lett);
        if (rightOnot == true) {

            NewCW(lett);
        }

        else {
            if(!wrongGuess.includes(lett)) {
                console.log("hi");
                wrongGuess.push(lett);
            }
            guessBomb -= 1;
        }
    }

    else if (lett.length < 1) {

    }

    else {
        guessBomb -= 1;
    }

    if (guessBomb <= 0) {
        gameLose()
    }

    if (winCount <= 0) {
        gameWin()
    }
    document.getElementById("rightGuess").innerHTML = "word progress: " + wordGuess;
    document.getElementById("wrongGuess").innerHTML = "Wrong guesses: " + wrongGuess;
    document.getElementById("guessesLeft").innerHTML = "Guesses remaining: " + guessBomb;
}

function isRightOnot(a) {
    var n = word.includes(a);
    return n;
}

function NewCW(letter) {
    var count = 0;
    winCount -= 1

    while (count <= word.length - 1) {
        if (letter === word[count]) {
            if(wordGuess[count] === letter) {
            }
            else {
            }

            wordGuess[count] = letter;
            count += 1;
        }

        else {
            count += 1;
        }

    }

}

function gameLose() {
    document.getElementById('mainGame').style.display='none';
    document.getElementById('RRguess').style.display='none';
    document.getElementById('youLose').style.display='block';
    document.getElementById("correctWordWas").innerHTML = "The correct word was " + word;
}

function gameWin() {
    document.getElementById('mainGame').style.display='none';
    document.getElementById('RRguess').style.display='none';
    document.getElementById('youWin').style.display='block';
}

function restart() {
    document.getElementById('mainGame').style.display='none';
    document.getElementById('RRguess').style.display='none';
    document.getElementById('youLose').style.display='none';
    document.getElementById('youWin').style.display='none';
    document.getElementById('chooseDifficulty').style.display='block';

    word = "";
    wordGuess = [];
    wrongGuess = [];
    guessBomb = 0;
    winCount = 1;
    guess = "";
    dif = 0;
}

Now the javascript code is also added successfully. In his code we first declare the variables for user input, entering correct word that matches and some points for win and loss with respective values given by the user. After that, we are getting each and every element declared in an html div tag with the java script get element property.

And now we creating a separate function with the name word(). Inside this function we declared the below values to match the user-entered letters with inbuilt letters declared.

var randomWords = ["humor", "miniature", "amusing", "creepy", "fact", "risk", "verse", "land", "lumpy", "holiday", "glorious", "weigh", "brake", "pretty", "grin", "capricious", "bite-sized", "misty", "ignore", "certain", "sloppy", "dress", "true", "zonked", "observation", "action", "various", "want", "direful", "suck", "dress", "scarecrow", "judge", "madly", "quizzical", "consist", "fierce", "love", "arrest", "serve", "fit", "hug", "tan", "curve", "eatable", "tub", "race", "innocent", "open", "preach", "steady", "acoustics", "lock", "field", "arrange", "rifle", "learned", "toe", "flow", "competition", "ill-fated", "oatmeal", "match", "male", "measure", "loaf", "smile", "wrestle", "dull", "food", "locket", "bell", "beg", "strengthen", "responsible", "enchanting", "loutish", "switch", "idea", "nine", "squeamish", "pig", "bat", "dear", "trains", "owe", "frogs", "assorted", "lonely", "hurry", "natural", "sun", "snow", "obnoxious", "broken", "friend", "bright", "cake", "sour", "permit", "economic", "lovely", "quick", "van", "tempt", "apparel", "decay", "business", "adjustment", "blushing", "makeshift", "slippery", "load", "winter", "exist", "tongue", "country", "roll", "fast", "moor", "possess", "pat", "pass", "books", "impartial", "hospitable", "dust", "naughty", "extra-large", "tacky", "produce", "committee", "fuzzy", "judicious", "nebulous", "stick", "ear", "copy", "friendly", "press", "distinct", "vegetable", "upset", "venomous", "statement", "sulky", "spell", "x-ray", "square", "taste", "great", "thumb", "adjoining", "chilly", "test", "ancient", "green", "badge", "work", "repeat", "free", "elderly", "doctor", "difficult", "grubby", "approval", "turn", "vivacious", "thundering", "cherries", "rest", "plan", "crime", "sticks", "wealthy", "phone", "suspend", "gullible", "fence", "note", "wall", "interest", "coil", "jump", "enchanted", "funny", "racial", "greasy", "polish", "elbow", "smart", "bore", "crowd", "glistening", "oval", "eggs", "nauseating", "detailed", "veil", "coal"]

From this set of words if the user letters were matched, then it adds the score for the winning and that is done by js itself.  Then with js math functions, we are matching the letter’s length with respective in-built letters.

So after this, if the guessed word is correct then it might show the color green if not then it shows red and all those particular elements were mentioned by the js property. For reference, the code is given below.

document.getElementById("rightGuess").innerHTML = "word progress: " + wordGuess;
    document.getElementById("wrongGuess").innerHTML = "Wrong guesses: " + wrongGuess;
    document.getElementById("guessesLeft").innerHTML = "Guesses remaining: " + guessBomb;
}

function isRightOnot(a) {
    var n = word.includes(a);
    return n;
}

function NewCW(letter) {
    var count = 0;
    winCount -= 1

    while (count <= word.length - 1) {
        if (letter === word[count]) {
            if(wordGuess[count] === letter) {
            }
            else {
            }

            wordGuess[count] = letter;
            count += 1;
        }

        else {
            count += 1;
        }

    }

}

function gameLose() {
    document.getElementById('mainGame').style.display='none';
    document.getElementById('RRguess').style.display='none';
    document.getElementById('youLose').style.display='block';
    document.getElementById("correctWordWas").innerHTML = "The correct word was " + word;
}

function gameWin() {
    document.getElementById('mainGame').style.display='none';
    document.getElementById('RRguess').style.display='none';
    document.getElementById('youWin').style.display='block';
}

Lastly, if we want to restart the game after winning/losing, the respective code helps to do it, which is given below.

function restart() {
    document.getElementById('mainGame').style.display='none';
    document.getElementById('RRguess').style.display='none';
    document.getElementById('youLose').style.display='none';
    document.getElementById('youWin').style.display='none';
    document.getElementById('chooseDifficulty').style.display='block';

    word = "";
    wordGuess = [];
    wrongGuess = [];
    guessBomb = 0;
    winCount = 1;
    guess = "";
    dif = 0;
}

Now we completed our javascript code successfully. Also, we now come to the end of this project but make sure to view the project preview from the given output section.

Final output of word guessing game:


Now we have successfully created our word guess game project with the help of html, css and javascript. You can use this project for your personnel needs and the respective lines of code is given with the code pen link mentioned below.

If you find out this blog helpful? , then make sure to search code with random on google for front-end projects with source codes and make sure to follow the codewithrandom Instagram page.

Refer code – Elel

Written by – ragunathan s



Leave a Reply