PROJECT 6
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.
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.
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:
https://jsfiddle.net/user/watzthis
.Locate the fiddle named Chapter 6 – Word Game, and click the title to open it.
The finished word game project will open up.
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.
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.
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.
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:
http://jsfiddle.net
in the new tab.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!
Now you’re ready to get started with the HTML for the program!
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.
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>
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>
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">
<br>Adjective
</li>
<!-- put other input fields here -->
HTML comments start with <!-- and end with -->.
<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>
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.
<button id="replaceButton">Replace it!</button>
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.
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!
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:
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";
}
For a list of other common font families, visit
www.w3schools.com/cssref/css_websafe_fonts.asp
.
#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.
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 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.
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.
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;
}
Click the Save button to save your work.
Your Result pane should now look like Figure 6-4.
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.
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.
function replaceIt() {}
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.
var adj1 = "<span class='replacement'>"+ document.getElementById("adj1").value + "</span>";
/* 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.
Create a variable that will be used to put the story together.
We’ll call the variable theStory.
var theStory;
theStory = "<h1>Douglas's Dance Party</h1>";
theStory += "One " + adj1 + " day,";
/* Put the rest of the story here, using the += operator */
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;
}
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.
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.
Figure 6-5: The generated story.
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:
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.
<li><input type="text" id="adj1" />
<br />Adjective</li>
Verb (ending in "-ing")
var adj1 = "<span class='replacement'>"+
document.getElementById("adj1").value + "</span>";
The new statement should now look like this:
var verbIng = "<span class='replacement'>"+
document.getElementById("verbIng").value + "</span>";
theStory += "One " + adj1 + " day,";
theStory += " Douglas was " + verbIng;
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.
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!