Games

See more about:

Where are we?

This chapter is about adding widgets to your site. We’ve looked at search, advertising, affiliate sales, and other things. This lesson looks at games.

You can use games that others have created. But you can also use games you write yourself. The advantage of doing it yourself is that you can customize the games to match the content and the look and feel of your site.

Let’s see how you can add a Mad Lib to your site.

This lesson’s goals

By the end of this lesson, you should:

  • Know what a Mad Lib is.
  • Understand the flow of a Mad Lib game.
  • Be able to create the input form and output story for a Mad Lib.
  • Be able to write the JavaScript code for a Mab Lib.

What is a Mad Lib?

The goal of a Mad Lib is to create a story. There are two people, the reader and the player. The reader has a piece of paper that looks something like this:

Mad Lib

Figure 1. Mad Lib

The reader asks the player for words to fill in the blanks.

Getting the words

Figure 2. Getting the words

The reader writes the words into the story. When all the blanks have been filled, the reader tells the completed story.

Telling the story

Figure 3. Telling the story

The result? Fun for all dogs! And young players learn a bit about language as well.

You can visit the official Mad Lib site. There’s a history of the game, Mab Lib books, and other stuff.

Game flow

Let’s make a Mad Lib game. The computer takes the part of the reader in Figure 2. The person is the player. The player fills in a form:

Input form

Figure 4. Input form

The player clicks the Go button, and gets the output:

Story output

Figure 5. Story output

You can try it. It isn’t a complete story. I just wanted enough to show you how it works.

Here is the overall pattern for game flow. You can see what the Web browser does and what the player (the user) does.

  1. Browser: Show the form
  2. Player: Complete the form
  3. Player: Click the Go button
  4. Browser: Get the player's input

    If the form is not complete, show an error and stop.

  5. Browser: Fill in the blanks in the story
  6. Browser: Show the story

Figure 6. Game flow

The player has to complete all of the fields in the form. If s/he does not, the browser shows an error message, and stops.

Making the input form

As Figure 4 shows, I wanted input fields that look like this:

Input field

Figure 7. Input field

Here’s the HTML for one field:

<p>
  The first name of someone you know (e.g., Tom).
  <input id="first_name1_in" type="text" size="20">
</p>

Figure 8. HTML for an input field

The field has an id, so that the JavaScript can easily get what the user entered into the field. The value of the id property – first_name1_in – says what the field is for. It’s a first name input. There are two first name input fields. This is number 1 of 2.

Renata
Renata

Could it have been called first_name_in1, or name_first_1_in?

Kieran
Kieran

Yes. Use whatever ids make sense to you, and that you think other Webers will understand. Just make sure they are descriptive.

For example, q43s would not be a very good id. The computer won’t care, but it makes the code harder for other Webers to understand.

There’s some CSS as well for styling. Setting the font family, background color, and such.

For each person’s name in Figure 4, I also wanted radio buttons for choosing gender:

Gender radio buttons

Figure 9. Gender radio buttons

Here’s some HTML.

<p id="html_for_gender_radio_buttons">
  Is this person male or female?<br>
  <input type="radio" name="gender1_in" id="gender1_in_male" value="male" checked="true"> Male<br>
  <input type="radio" name="gender1_in" id="gender1_in_female" value="female"> Female<br>
</p>

Figure 10. HTML for gender radio buttons

There are two <input> fields, one for each radio button. The first one has checked="true", so it is checked when the page first displays.

Each radio button has a name property and an id property. The names are the same, but the ids are different. What’s going on?

Radio buttons usually don’t work alone. They work in groups. Only one radio button in a group can be selected at a time.

Here are two button groups. Pick your favorite animal and food below.

Cat
Dog
Horse

Chocolate
Dog biscuits
Ice cream
Pizza

Figure 11. Some radio buttons

Click on all the options. In the first group, you can only select one animal. In the second group, you can only select one food.

How does the browser know which buttons form a group? By the name property.

All of the animal radio buttons start like this:

<input type="radio" name="animal"

All of the food radio buttons start like this:

<input type="radio" name="food"

When there are several radio buttons with the same name, the browser will only let one of them be selected.

Suppose I change all of the names of the radio buttons in Figure 11 to the same thing. Let’s make them all bark. The HTML for all the buttons starts this way:

<input type="radio" name="bark"

Here’s what you get:

Cat
Dog
Horse

Chocolate
Dog biscuits
Ice cream
Pizza

Figure 12. Messed up radio buttons

Try clicking on all the radio buttons.

Because they all have name="bark", they are all part of the same group. So only one of them can be selected.

Here’s another way to mess things up. Suppose I give all of the buttons different names. The first one is thing1, the next is thing2, the next thing3, and so on, up to thing7.

Try clicking on these buttons.

Cat
Dog
Horse

Chocolate
Dog biscuits
Ice cream
Pizza

Figure 13. More messed up radio buttons

Because each button has a different name, each one is in a different group.

OK, so you know that the name property defines a group. But how can your JavaScript code tell which button within a group is checked?

Here’s the gender code again:

<p id="html_for_gender_radio_buttons">
  Is this person male or female?<br>
  <input type="radio" name="gender1_in" id="gender1_in_male" value="male" checked="true"> Male<br>
  <input type="radio" name="gender1_in" id="gender1_in_female" value="female"> Female<br>
</p>

Figure 10 (again). HTML for gender radio buttons

The id properties are different for male and female. You can write JavaScript to use them. We’ll see that in a moment.

Renata
Renata

There’s also a value property in each of them.

Kieran
Kieran

Good eye. The value isn’t used here. It’s for sending data to the server. We’ll talk about that in ServerCore.

Here is all the HTML for the input form:

<div id="input_stuff">
  <p>Please fill in the fields and click <strong>Go</strong>.</p>
  <p>
    The first name of someone you know (e.g., Tom).
    <input id="first_name1_in" type="text" size="20">
  </p>
  <p>
    Is this person male or female?<br>
    <input type="radio" name="gender1_in" id="gender1_in_male" value="male" checked="true"> Male<br>
    <input type="radio" name="gender1_in" id="gender1_in_female" value="female"> Female<br>
  </p>
  <p>
    The first name of another person you know (e.g., Rita).
    <input id="first_name2_in" type="text" size="20" checked="true">
  </p>
  <p>
    Is this person male or female?<br>
    <input type="radio" name="gender2_in" id="gender2_in_male" value="male" checked="true"> Male<br>
    <input type="radio" name="gender2_in" id="gender2_in_female" value="female"> Female<br>
  </p>
  <p>
    A color (e.g., blue).
    <input id="color1_in" type="text" size="20">
  </p>
  <p>
    Animal, plural (e.g., penguins).
    <input id="animal1_in" type="text" size="20">
  </p>
  <p>
    Another animal, plural (e.g., moles).
    <input id="animal2_in" type="text" size="20">
  </p>
  <p>
    <button id="go_button" title="Tell story">Go</button>
  </p>
</div>

Figure 14. HTML for the input form

Notice that the entire input form is wrapped in a <div> (line 1). This lets JavaScript hide the form in one step.

Making the output area

Let’s look at the part of the page that shows the output, that is, the story with the blanks filled in. Here’s what the paper version looks like.

Mad Lib

Figure 1 (again). Mad Lib

We need to give each of the blank spots an id. Then we can use JavaScript to put text in there. The <span> tag is good for that.

Here’s all the code for the output area.

<div id="story">
  <p>
    <span id="first_name1_out"></span>&nbsp;was walking in the park one day,
    humming to <span id="gender1_out"></span>self. The day was bright, the
    sun was shining, and the <span id="animal1_out"></span>&nbsp;were singing.
  </p>
  <p>
    Suddenly, two <span id="color1_out"></span>&nbsp;<span id="animal2_out"></span> ran by.
  </p>
  <p>
    "Run! Run!" they cried. "<span id="first_name2_out"></span>&nbsp;is coming!
    And <span id="gender2_out"></span>'s really angry!"
  </p>
  <p>
    <button id="reset_button" title="Show input fields again">Reset</button>
  </p>
</div>

Figure 15. HTML for the output area

Have a look at line 3. The blank for the first name is created with this:

<span id="first_name1_out"></span>

There’s no text in the <span>. We’ll write some JavaScript to fill it in from the form.

But what about the thing that follows the </span>?

...</span>&nbsp;was...

The &nbsp; is a hard space. We should be able to put just:

...</span> was...

That should work, and it does in most browsers. But when Internet Explorer and jQuery are used together, the space gets gobbled up. So we have to use the HTML entity code &nbsp; to force the space to appear.

The JavaScript

Let’s review the overall flow of the game.

  1. Browser: Show the form
  2. Player: Complete the form
  3. Player: Click the Go button
  4. Browser: Get the player's input

    If the form is not complete, show an error and stop.

  5. Browser: Fill in the blanks in the story
  6. Browser: Show the story

Figure 6 (again). Game flow

Let’s write the JavaScript for the Go button. It needs to do steps 4, 5, and 6.

Here’s code that will get the value of an input field and check whether it’s empty.

var first_name1_in = $("#first_name1_in").val();
if ( first_name1_in == "") {
  alert("Please complete all fields.");
  $("#first_name1_in").focus();
  return;
}

Figure 16. Check that a field was completed

Line 1 gets the value the user typed into the field, and puts it in a variable.

Line 2 checks whether the user put anything in the field. If the field is empty, the variable will be equal to an empty string: "".

If the field is empty, show an error message (line 3). Then put the input focus into the empty field (line 4). The user can then start typing, without having to click on the field him/herself.

Line 5 is important. This stops the $("#go_button").click() function from going any further.

All of the text input fields are checked for missing data. The pattern in Figure 16 is repeated for each text input field.

In fact, these checks make up most of the code in the $("#go_button").click() function. It’s common for most of the code in a program to be error checking.

We also need to get the data from the gender radio buttons. As a reminder, here is some HTML for one of the buttons. It creates a group of two radio buttons.

<p id="html_for_gender_radio_buttons">
  Is this person male or female?<br>
  <input type="radio" name="gender1_in" id="gender1_in_male" value="male" checked="true"> Male<br>
  <input type="radio" name="gender1_in" id="gender1_in_female" value="female"> Female<br>
</p>

Figure 10 (again). HTML for gender radio buttons

The user tells us whether a person is male or female. How do we use this? Here’s part of the HTML for the story:

humming to <span id="gender1_out"></span>self.

We want gender1_out to be “him” for a male, or “her” for a female.

Here’s some JavaScript to get the value of this radio button group, and create a variable with the text we want to show.

var gender1_out;
if ( $("#gender1_in_male").is(":checked") ) {
  gender1_out = "him";
}
else {
  gender1_out = "her";
}

Figure 17. Compute gender pronoun

The syntax in line 2 is a little strange. gender1_in_male is the id of one of the radio buttons in the group. is(":checked") is true if that button is checked.

There are two radio button groups in the input form:

Input form

Figure 4 (again). Input form

So we have another version of Figure 17 for the other group.

We have two more steps in the game flow:

  1. Browser: Show the form
  2. Player: Complete the form
  3. Player: Click the Go button
  4. Browser: Get the player's input

    If the form is not complete, show an error and stop.

  5. Browser: Fill in the blanks in the story
  6. Browser: Show the story

Figure 6 (again). Game flow

Here’s some HTML for the story:

<p>
  "Run! Run!" they cried. "<span id="first_name2_out"></span>>nbsp;is coming!
  And <span id="gender2_out"></span>'s really angry!"
</p>

Figure 18. Part of the HTML for the output area (from Figure 15)

We put the text of each input field into a variable, like this (from Figure 16):

var first_name2_in = $("#first_name2_in").val();

We put each gender pronoun into a variable, like this (from Figure 17):

gender1_out = "him";

Here is some JavaScript for using these variables to fill in part of the story:

$("#first_name2_out").text(first_name2_in);
$("#gender2_out").text(gender2_out);

Figure 19. Filling in the story

The code puts the values from the variables into the appropriate <span>s.

There is one more step in the game flow:

  1. Browser: Show the form
  2. Player: Complete the form
  3. Player: Click the Go button
  4. Browser: Get the player's input

    If the form is not complete, show an error and stop.

  5. Browser: Fill in the blanks in the story
  6. Browser: Show the story

Figure 6 (again). Game flow

Here’s code to hide the input form, and show the output area.

$("#input_stuff").hide();
$("#story").show();

Figure 20. Hiding the input form and showing the story

I added something else to the end of the story:

Story output

Figure 5 (again). Story output

The Reset button just hides the output area (the story) and shows the input form again. This lets the user make a quick changes to the story.

Here’s the HTML and the JavaScript:

<div id="story">
...
  <p>
    <button id="reset_button" title="Show input fields again">Reset</button>
  </p>
</div>
...
$(document).ready(function() {
...
  $("#reset_button").click(function() {
    $("#story").hide();
    $("#input_stuff").show();
  });
});

Figure 21. The Reset button

Notice that the HTML for the <button> is inside the story element. So the user only sees it when the story is shown.

The JavaScript is simple. It hides the story, and shows the input form.

Remember that you can try the game. It isn’t a complete story. I just wanted enough to show you how it works.

Here’s all the JavaScript. It includes a few extra details.

$(document).ready(function() {
  $("#story").hide();
  $("#first_name1_in").focus();
  $("#go_button").click(function() {
    //Check that all the fields are completed.
    var first_name1_in = $("#first_name1_in").val();
    if ( first_name1_in == "") {
      alert("Please complete all fields.");
      $("#first_name1_in").focus();
      return;
    }
    var first_name2_in = $("#first_name2_in").val();
    if ( first_name2_in == "") {
      alert("Please complete all fields.");
      $("#first_name2_in").focus();
      return;
    }
    var color1_in = $("#color1_in").val();
    if ( color1_in == "") {
      alert("Please complete all fields.");
      $("#color1_in").focus();
      return;
    }
    var animal1_in = $("#animal1_in").val();
    if ( animal1_in == "") {
      alert("Please complete all fields.");
      $("#animal1_in").focus();
      return;
    }
    var animal2_in = $("#animal2_in").val();
    if ( animal2_in == "") {
      alert("Please complete all fields.");
      $("#animal2_in").focus();
      return;
    }
    //Get genders
    var gender1_out;
    if ( $("#gender1_in_male").is(":checked") ) {
      gender1_out = "him";
    }
    else {
      gender1_out = "her";
    }
    var gender2_out;
    if ( $("#gender2_in_male").is(":checked") ) {
      gender2_out = "he";
    }
    else {
      gender2_out = "she";
    }
    //Fill in the story
    $("#first_name1_out").text(first_name1_in);
    $("#first_name2_out").text(first_name2_in);
    $("#color1_out").text(color1_in);
    $("#animal1_out").text(animal1_in);
    $("#animal2_out").text(animal2_in);
    $("#gender1_out").text(gender1_out);
    $("#gender2_out").text(gender2_out);
    //Hide the input area
    $("#input_stuff").hide();
    //Show the story
    $("#story").show();
  });
  $("#reset_button").click(function() {
    //Hide the story
    $("#story").hide();
    //Show the input area
    $("#input_stuff").show();
  });
});

Figure 22. All of the JavaScript

Lines 2 and 3 are executed when the page loads. Line 2 hides the story. We only want the input form showing at the start. Line 3 puts the input focus on the first form field. The user is ready to type, without having to click on anything.

Notice that there are comments throughout the code. Comments are a Good Thing. When the code needs to be changed, the comments will help the person making the changes understand how the code works. S/he can then make changes quickly and accurately.

Context-specific Mad Libs

One of the nice things about Mab Libs is that you can customize them. You can match them to your organization.

Suppose you have characters on your Web site, like, I don’t know, Kieran, CC, and Renata. Instead of having the user type in a name, you could have him/her select from a set of existing names.

Here is some HTML and JavaScript for a story that only makes sense on CoreDogs.

<p>
  A first name.<br>
  <input type="radio" name="first_name1_in" id="first_name1_in_cc" value="cc" checked="true"> CC<br>
  <input type="radio" name="first_name1_in" id="first_name1_in_kieran" value="kieran"> Kieran<br>
  <input type="radio" name="first_name1_in" id="first_name1_in_renata" value="renata"> Renata<br>
</p>
...
<p>
  <span id="first_name1_out"></span> was walking in the park one day,
  humming to <span id="gender1_out"></span>self. ...
</p>
...
$("#go_button").click(function() {
  var first_name1_out;
  var gender1_out;
  if ( $("#first_name1_in_cc").is(":checked") ) {
    first_name1_out = "CC";
    gender1_out = "her";
  }
  if ( $("#first_name1_in_kieran").is(":checked") ) {
    first_name1_out = "Kieran";
    gender1_out = "him";
  }
  if ( $("#first_name1_in_renata").is(":checked") ) {
    first_name1_out = "Renata";
    gender1_out = "her";
  }
  ...
  $("#first_name1_out").text(first_name1_out);
  $("#gender1_out").text(gender1_out);
  ...
});

Figure 23. Context-specific Mad Lib

This creates:

CoreDogs names

Figure 24. CoreDogs names

These radio buttons replace both the first name field and the gender radio buttons. We can compute gender. We don’t need to ask the user.

You can customize Mad Libs to your own company, school, etc. Use people and things that make sense in your context.

Other ways to add games

This lesson showed how to create a Mad Lib for your Web site. But there are many other ways to add games.

Sites like FreeGamesJungle have Flash games you can add to your site. There are also plenty of JavaScript games available. The JavaScript Source has a bunch.

JavaScriptGaming has some very interesting stuff. Including some first-person shooters in JavaScript! They show how capable JavaScript is in today’s browsers.

Summary

This lesson showed you:

  • What a Mad Lib is.
  • The flow of a Mad Lib game.
  • How to create the input form and output story for a Mad Lib.
  • How to write the JavaScript code for a Mab Lib.

What now?

Let’s finish up by looking at some other widgets you could add to your site.


How to...

Lessons

User login

Log in problems? Try here


Dogs