Chapter 10

Creating Your Own JavaScript Word Game

Word replacement games give you a basic story structure and ask you to supply different parts of speech: nouns, verbs, adjectives, adverbs, and so on. If you think about it, these games are very similar to JavaScript web apps. The basic structure is provided by the HTML, the CSS, and the JavaScript code. The variables in the JavaScript code are what make the results of the program different every time it’s run.

In this chapter, we create a word replacement game by using the string concatenation operator to combine the words you enter with a story.

image

Creating a Variable Story

For this first version of the game, we wrote a story about Douglas the JavaScript Robot’s adventures. Then we removed some of the words and replaced them with just a part of speech, 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 input expected (underlined):

  • One adjective day, Douglas was verb ending in “–ing” in his room in house, reading a book about color plural noun.
  • As he past-tense verb his beverage, he heard type of music music playing in the different room in house.
  • exclamation! he exclaimed, as he past-tense verb down the stairs to join the adjective party.
  • Douglas danced the name of animal Dance, the name of city Twist, and took the prize for dancing the best Electric verb.

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 so far 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 http://jsfiddle.net/user/forkids/fiddles.
  2. Locate the fiddle named Chapter 10 – Word Replacement Game, and click the title to open it.

    The finished Word Replacement 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.

    The labels for the underlined input areas on the left should all fit on the screen without wrapping to new lines. You should also 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 value in the input field.

    After you’ve entered the desired value, 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 10-1.

image

Figure 10-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 Replacement Game from scratch:

  1. Open a new browser tab by selecting New Tab from the Chrome menu or pressing maccmd+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.

    For example, you might call it Douglas’s Dance Party.

  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 question area: This is the input area where the program prompts you to enter words.
  • The button area: This is the area at the bottom of the questions that contains the Replace It button that will add your input into the story.
  • The story area: This is the area where the user input and the story appear together after the Replace It button is clicked.

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

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

    Each <div> will have a unique id attribute that correlates with 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>

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

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

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

    <ul>

      <li></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" />

    tip Notice that we put a slash (/) before the closing bracket in the input field. Although it’s not required in HTML5, JSFiddle tends to format HTML markup better when you do use the slash at the end of elements like <input> and <br>.

  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 -->

    remember 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 Update to see what the output of the web application is now.

    It should look like Figure 10-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 Update again.

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

image

Figure 10-2: The beginning of the Word Replacement Game.

image

Figure 10-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

Before we jump right into styling, let’s talk about organizing our CSS.

When you’re using a lot of CSS for an application, it’s important to organize it in some way so that you’ll be able to easily find styles later on when you want to edit them.

One way to organize CSS files is by what section of the HTML document they apply to. Typically, this method will list CSS styles in roughly the same order as the elements that they apply to in the HTML.

Following this method, the first element for us to style is the body element, followed by the container for the input fields, followed by the list, followed by the input fields, and so on.

So, let’s get styling. Follow these steps to apply styles to the Word Replacement 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 Update to see the latest version of the app.

    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 Update button to save your work.

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

image

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

There is much more to creating a good JavaScript web application than just JavaScript code. But now that we’ve got those pieces 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 covered in Chapter 7.

var replaceButton = document.getElementById("replaceButton");

replaceButton.addEventListener("click",replaceIt);

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

Now let’s create the replaceIt function.

  1. Write an empty function definition for the function named replaceIt.

    function replaceIt() {}

  2. Inside the curly brackets, enter a line break and then create a variable to reference the <div> element 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 retrieve 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>";

    Notice that we’re using the string concatenation operator to surround the value (which we get using document.getElementById) with an HTML <span> element. The program uses this <span> element to style user input differently from the other text in the story.

  4. Write a comment after the creation of the adj1 variable.

    /* Insert more variable definitions here */

    The comment will remind you that you need to come back to this spot later to put a variable for every other HTML input field that you add to the HTML pane later.

  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 the 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 combination concatenation/assignment operator, +=.

    This operator adds the new value to any value that’s already stored in the variable.

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

  8. Once again, leave a comment for yourself to remind you that you need to come back and add the rest of the story after you get the basic functionality all working.

    /* 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.

Now, the moment you’ve been waiting for! Press Update in the top menu to see the first version of the Word Replacement 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 10-5.

image

Figure 10-5: The generated story.

Finishing the program

You now have all the components of the Word Replacement 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 Update.

    When you test out the program now, it should look like Figure 10-6. Congratulations, you’ve added a second question to the game!

    Repeat the preceding ten steps to add more questions to your game. When it’s complete, the markup in your HTML pane should match the markup in Listing 10-1, and the code in your JavaScript pane should match Listing 10-2.

Listing 10-1 The Completed Markup in the HTML Pane

<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>

Listing 10-2 The Completed Code in the JavaScript Pane

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 10-6.

image

Figure 10-6: The working Word Replacement Game.

Now that you have a working copy of our Word Replacement Game, feel free to use the Fork button in the top menu to make a copy and try customizing it to tell your own story!

If your program doesn’t work as you expect it, check your code carefully and compare it with ours line by line. The problem is probably just a small typo. Visit www.dummies.com/extras/javascriptforkids to read our tips on debugging JavaScript programs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset