PROJECT 6

CREATING A JAVASCRIPT WORD GAME

image

WORD REPLACEMENT GAMES GIVE YOU A BASIC STORY AND ASK PLAYERS TO FILL IN THE DIFFERENT PARTS, SUCH AS NOUNS, VERBS, ADJECTIVES, AND SO ON. We use HTML, CSS, and JavaScript code to create the basic skeleton of the story. The variables in the JavaScript code are what make the results of the program different every time it’s run.

CREATING A VARIABLE STORY

To create this game, we wrote a story about Douglas the JavaScript Robot’s adventures. Then we removed some of the words so that the person playing the game can fill them in.

Here’s our story about Douglas the JavaScript Robot, with certain words removed and replaced with the type of word the program needs from the player (underlined):

Now that we have the story, let’s build a JavaScript program around it that will accept input from a user and output a customized — and hilarious — story.

CREATING THE WORD REPLACEMENT GAME

The word replacement game makes use of everything you’ve learned in this book, including variables, operators, event handlers, HTML, CSS, input, output, and more!

Before we jump into the building of the game, let’s try it out and see it in action:

  1. Open your web browser and go to our JSFiddle Public Dashboard at https://jsfiddle.net/user/watzthis.
  2. Locate the fiddle named Chapter 6 – Word Game, and click the title to open it.

    The finished word game project will open up.

  3. Depending on your screen size, you may need to adjust the size of the Result pane so that it fits correctly.

    You should see a very short rectangle with a dotted border to the right of the input questions. This is where the finished story will display.

  4. Click the underline right above the first question to select the text input field.
  5. Enter a word in the input field.

    After you’ve entered the word you like, press the Tab key or use your mouse to click the next input field on the page and fill that one out.

  6. When you’ve finished filling out all the fields, click the Replace It button at the bottom of the form.

The story of Douglas’s adventure appears on the right with the words you entered into the input fields inserted, as shown in Figure 6-1.

image

Figure 6-1: The finished story of Douglas’s adventure.

Now that you’ve seen how the program works, let’s start from scratch and build it. When you know how to build the game, you’ll be able to add to it, improve it, and even change the story completely!

Follow these steps to begin creating your own version of the word game:

  1. Open a new browser tab by selecting New Tab from the Chrome menu or pressing ⌘+C (Mac) or Ctrl+C (Windows) and go to http://jsfiddle.net in the new tab.
  2. Make sure that you’re logged in to JSFiddle by checking whether your username is in the upper-right corner of the screen.

    When you’re logged in, you’re ready to go!

  3. Click the Fiddle Options link in the left navigation bar and enter a name for your new program.
  4. Click Save in the top menu.

Now you’re ready to get started with the HTML for the program!

WRITING THE HTML

Our word replacement game has three main areas, or sections:

The first thing we’ll do is to create these three areas. We’ll create each section using a <div> element.

  1. Enter two <div> elements into the HTML pane.

    Each <div> will have a unique ID attribute that names its purpose. Our first <div> will have an ID of inputWords. We want the second <div> to be inside of the first <div>, and we’ll give it an ID of buttonDiv, as shown here:

    <div id="inputWords">

    <div id="buttonDiv"></div>

    </div>

  2. Next, create a structure for the input fields.

    We’ll use an HTML list to hold all the input fields. Use the following HTML markup inside the first <div> to create the structure:

    <ul>
    <li>
    </ul>

  3. Create the first input field inside of the <li> element.

    Use the input element, with type=text" and id="adj1", like this:

    <input type="text" id="adj1">

  4. Put a label underneath the input field by using a <br> tag, followed by the label, like this:

    <br>Adjective

  5. Finally, close the <li> element by putting the following ending tag after the word Adjective:

    </li>

  6. Put an HTML comment on the next line to serve as a placeholder for the other input fields that you’ll add to the program later on.

    <!-- put other input fields here -->

    tip HTML comments start with <!-- and end with -->.

  7. Type the third <div> element underneath all the other markup in the HTML pane.

    <div id="story"></div>

    If you’ve entered everything correctly, your HTML pane should now look like the following:

    <div id="inputWords">
    <ul>
     <li><input type="text" id="adj1"><br>Adjective</li>
    <!-- put other input fields here -->
    </ul>
    <div id="buttonDiv"></div>
    </div>
    <div id="story"></div>

  8. Click Run to see what your word game looks like so far.

    It should look like Figure 6-2.

    The final step that we’ll do in the HTML pane for now is to create the button.

  9. Place your cursor inside the <div> with the ID of buttonDiv, and type the following:

    <button id="replaceButton">Replace it!</button>

  10. Click Run again.
image

Figure 6-2: The beginning of the word game.

You now have a single input field, a label under that field, and a button underneath both of them, as shown in Figure 6-3.

image

Figure 6-3: The essential components are in place.

Because all the rest of the input fields are just copies of this first one, we won’t walk you through how to create all those. You can copy the first input field to create the rest of them, or feel free to copy them from the HTML pane in our finished version of the program.

Let’s move on to the CSS pane!

STYLING THE WORD GAME

There’s much more to creating a good JavaScript program than just JavaScript code. Let’s use CSS to make our word game more stylish.

Follow these steps to apply CSS styles to the word game:

  1. To change the typeface of all the text in the document, apply a font-family style to the body element.

    We’re going to use the super-fun Comic Sans typeface:

    body {
    font-family: "Comic Sans MS";
    }

    tip For a list of other common font families, visit www.w3schools.com/cssref/css_websafe_fonts.asp.

  2. Style the section containing the input fields with the following rule:

    #inputWords {
    float:left;
    width: 45%;
    }

    The float:left property in this rule causes the <div> to be placed along the left edge of its container (which is the document’s body element in this case). Other elements will flow around it.

    In practice, what float:left will do is to cause the <div> containing the input questions to be placed to the side of the <div> that will contain the finished story, rather than above it.

  3. Style the list using the following two rules:

    ul {
    list-style-type: none;
    padding: 0px;
    margin: 0px;
    }
    li {
    line-height: 2em;
    text-transform: uppercase;
    margin-top: 8px;
    }

    Here’s what each of the properties in these rules does to the list:

    • The list-style-type property removes the dot (bullet) from the left of each item in the list.
    • Setting the padding and margin to 0px makes the list left aligned with the other text on the page.
    • Setting the line-height of the <li> creates more space between list items. Without this property, the elements would be uncomfortably close to each other.

    The text-transform property of the <li> element causes all the input field labels underneath the input field to display as all capital letters.

    The margin-top property creates yet more space between list items.

  4. With these new CSS rules in place, click Run to see the latest version of the game.

    The next few styles apply some formatting to the input fields, the button, and the story.

  5. Type the following into the CSS pane:

    input[type=text] {
    border-width: 0 0 1px 0;
    border-color: #333;
    }
    #buttonDiv {
    text-align: center;
    }
    #replaceButton {
    margin-top: 30px;
    width: 200px;
    }
    #story {
    margin-top: 12px;
    width: 45%;
    border: 1px dashed blue;
    padding: 8px;
    float: left;
    }
    .replacement {
    text-decoration: underline;
    text-transform: uppercase;
    }

  6. Click the Save button to save your work.

    Your Result pane should now look like Figure 6-4.

image

Figure 6-4: The Result pane with all the CSS styles applied.

Now that we have our HTML and CSS in place, we’re ready to move on to the JavaScript.

WRITING THE JAVASCRIPT CODE

The first thing we’ll do in the JavaScript pane is to create an event handler for the button. We’ll use the addEventListener method.

var replaceButton = document.getElementById("replaceButton");
replaceButton.addEventListener("click",replaceIt);

This first line creates a variable (replaceButton) to hold the location of the button element. The second line uses that variable to attach a function (replaceIt) to an event (click).

Now let’s create the replaceIt function.

  1. Give the function a name of replaceIt.

    function replaceIt() {}

  2. Inside the curly braces, press Return (Mac) or Enter (Windows) to move to the next line and then create a variable to hold the location where the finished story will appear.

    var storyDiv = document.getElementById("story");

    We’ll come back and use the storyDiv variable in a moment. For now, our next task is to get the values from the HTML input fields.

  3. Create a variable to hold the value of the first HTML input field.

    var adj1 = "<span class='replacement'>"+ document.getElementById("adj1").value + "</span>";

  4. Write a comment after the adj1 variable.

    /* Insert more variables here */

    This comment will remind you that you need to come back to this spot later to make a variable for the other input fields.

  5. Create a variable that will be used to put the story together.

    We’ll call the variable theStory.

    var theStory;

  6. Put the title of your story into theStory, and put the title into an <h1> element.

    theStory = "<h1>Douglas's Dance Party</h1>";

  7. Add the first part of the story to theStory by using the += operator.

    theStory += "One " + adj1 + " day,";

  8. Leave a comment for yourself to remind you that you need to come back and add the rest of the story later.

    /* Put the rest of the story here, using the += operator */

  9. Use innerHTML to display the value of theStory inside the div we created for the story.

    storyDiv.innerHTML = theStory;

    With this line written, the code inside the JavaScript pane should now look like the following:

    var replaceButton = document.getElementById("replaceButton");
    replaceButton.addEventListener("click", replaceIt);

    function replaceIt() {
    var storyDiv = document.getElementById("story");
    var adj1 = "<span class='replacement'>" + document.getElementById("adj1").value + "</span>";
    /* Insert more variable definitions here */
    var theStory = "<h1>Douglas's Dance Party</h1>";
    theStory += "One " + adj1 + " day,";
    /* Put the rest of the story here, using the += operator */
    storyDiv.innerHTML = theStory;
    }

    tip If your code isn’t as nicely formatted as this JavaScript code, click the TidyUp button in the top menu. This button does exactly what you would think: It cleans everything up, sets all the tabs nicely, and makes your code easier to read and work with.

  10. Now, the moment you’ve been waiting for: Press Run in the top menu to see the first version of the word game in action!

Try entering a word into the input field and then press the Replace It button to see the results of your hard work, as shown in Figure 6-5.

image

Figure 6-5: The generated story.

FINISHING THE PROGRAM

You now have all the components of the word game in place. Finishing it is just a matter of repeating the following three steps for each additional word that the player needs to input:

  1. Make a copy of an input field and update the value of the id attribute and the label.
  2. Make a copy of the JavaScript statement containing getElementById and change the variable name and the value in parentheses.
  3. Add more text, containing the new variable, to the theStory variable.

Let’s try out these three steps to add the next part of the story (a verb ending in “–ing”) to the game.

  1. Select the following code in your HTML pane and make a copy of it.

    <li><input type="text" id="adj1" />
    <br />Adjective</li>

  2. Paste the copy of your code on the line after the original.
  3. Change the value of the id attribute to verbIng.
  4. Change the label after the input field to the following:

    Verb (ending in "-ing")

  5. In the JavaScript pane, make a copy of the following statement:

    var adj1 = "<span class='replacement'>"+
    document.getElementById("adj1").value + "</span>";

  6. Paste the code you copied onto the line after the original.
  7. Change the variable name to verbIng and change the value inside the parentheses after getElementById to verbIng.

    The new statement should now look like this:

    var verbIng = "<span class='replacement'>"+
    document.getElementById("verbIng").value + "</span>";

  8. Make a copy of the following statement:

    theStory += "One " + adj1 + " day,";

  9. Paste your copy on the next line and modify it to match the following:

    theStory += " Douglas was " + verbIng;

  10. Save your work by clicking Save.

Congratulations! You’ve added a second question to the game!

Repeat those ten steps to add more questions to your game. When it’s complete, your HTML pane should match the following:

<div id="inputWords">
<ul>
<li><input type="text" id="adj1" /><br>Adjective</li>
<li><input type="text" id="verbIng" /><br>Verb (ending in "-ing")</li>
<li><input type="text" id="roomInHouse" /><br>Room in a house</li>
<li><input type="text" id="color" /><br>Color</li>
<li><input type="text" id="nounPlural" /><br>Plural noun</li>
<li><input type="text" id="pastVerb" /><br>Verb (past tense)</li>
<li><input type="text" id="beverage" /><br>Beverage</li>
<li><input type="text" id="musicType" /><br>Type of music</li>
<li><input type="text" id="diffRoom" /><br>Different room in a house</li>
<li><input type="text" id="exclamation" /><br>Exclamation</li>
<li><input type="text" id="pastVerb2" /><br>Verb (past tense)</li>
<li><input type="text" id="adjDance" /><br>Adjective</li>
<li><input type="text" id="animal" /><br>Animal</li>
<li><input type="text" id="city" /><br>City</li>
<li><input type="text" id="verb" /><br>Verb</li>
</ul>
<div id="buttonDiv">
<button id="replaceButton">Replace it!</button>
</div>
</div>

<div id="story"></div>

The code in your JavaScript pane should match the following:

var replaceButton = document.getElementById("replaceButton");
replaceButton.addEventListener("click",replaceIt);

function replaceIt() {
var storyDiv = document.getElementById("story");
var adj1 = "<span class='replacement'>"+ document .getElementById("adj1").value + "</span>";
var verbIng = "<span class='replacement'> "+ document.getElementById("verbIng").value + "</span>";
var roomInHouse = "<span class='replacement'> "+ document.getElementById("roomInHouse") .value + "</span>";
var color = "<span class='replacement'>"+ document.getElementById("color").value + "</span>";
var nounPlural = "<span class='replacement'> "+ document.getElementById("nounPlural") .value + "</span>";
var pastVerb = "<span class='replacement'> "+ document.getElementById("pastVerb").value + "</span>";
var beverage = "<span class='replacement'> "+ document.getElementById("beverage").value + "</span>";
var musicType = "<span class='replacement'> "+ document.getElementById("musicType") .value + "</span>";
var diffRoom = "<span class='replacement'> "+ document.getElementById("diffRoom").value + "</span>";
var exclamation = "<span class='replacement'> "+ document.getElementById("exclamation") .value + "</span>";
var pastVerb2 = "<span class='replacement'> "+ document.getElementById("pastVerb2") .value + "</span>";
var adjDance = "<span class='replacement'> "+ document.getElementById("adjDance").value + "</span>";
var animal = "<span class='replacement'> "+ document.getElementById("animal").value + "</span>";
var city = "<span class='replacement'>"+ document .getElementById("city").value + "</span>";
var verb = "<span class='replacement'>"+ document .getElementById("verb").value + "</span>";

var theStory = "<h1>Douglas's Dance Party</h1>";
theStory += "One " + adj1 + " day,";
theStory += " Douglas was " + verbIng;
theStory += " in his " + roomInHouse;
theStory += ", reading a book about " + color;
theStory += " " + nounPlural + ".<br><br>";
theStory += "As he " + pastVerb;
theStory += " his " + beverage;
theStory += ", he heard " + musicType;
theStory += " music playing in the " + diffRoom + ".<br><br>";
theStory += exclamation + "! he exclaimed, as he ";
theStory += pastVerb2 + " down the stairs to join the ";
theStory += adjDance + " party.<br><br>";
theStory += "Douglas danced the " + animal;
theStory += " Dance, the " + city + " Shake,";
theStory += " and took the prize for dancing the best Electric " + verb + ".<br><br>";

storyDiv.innerHTML = theStory;

}

After you’ve finished entering all the questions and the JavaScript code to generate the whole story, it will replace all the blanks in the story with words you enter into the input fields, as shown in Figure 6-6.

image

Figure 6-6: The working word replacement game.

Now that you have a working word game, feel free to use the Fork button in the top menu to make a copy and try changing it to tell your own story.

Congratulations on completing all the projects! If you’ve made it this far, you’re well on your way to becoming a coding master! Happy coding!