Flash Explained

Learn Flash easily.

Creating a dynamic hangman game in Flash 8 with XML and ActionScript – part 2 of 4

This is the second part of the ActionScript hangman game lesson.

Loading data from a text file into Flash using the LoadVars object

54 Make a new layer and call it actions. Lock it, since a layer in Flash doesn not need to be unlocked for you to enter ActionScript code inside it. Click on the layer’s first (and only) keyframe to select it for code inserting.

The fourth and last layer in this project has been inserted.

55 Select Window > Actions to open the Actions panel. Insert the following ActionScript code inside it:

guessWord_txt._visible = false;
var welcomePart1:String = "Welcome to the hangman game! To, win you must try to guess the name of ";
var welcomePart2:String = ". Press the play button below to start.";
var guessTopic:LoadVars = new LoadVars();
guessTopic.onLoad = function(success:Boolean) {
if (success) {
startScreen_mc.message_txt.text = welcomePart1+this.myTopic+welcomePart2;
} else {
startScreen_mc.message_txt.text = "The data failed to load. I am sorry!";
}
};
guessTopic.load("guessword.txt");

The first line effectively hides the guessWord_txt text field by setting its _visible property to false. It will be made visiblke once the player presses the play button, the functionality of which will be defined later.

The second and the third line define the welcomePart1 and welcomePart2 variables. Both are defined as String variables, which means that they will hold text values. And these text values are assigned to them immediately. They are, respectively:

  • "Welcome to the hangman game! To, win you must try to guess the name of " and
  • ". Press the play button below to start."

They may appear a little strange. If you look at them closely, you will see that the first one ends with a space and that the second one starts with a fullstop, followed by a space and another sentence. This is because they will both be parts of the welcome message, once the game loads. The third piece of information for the welcome message will be loaded from an external text file.

The main reason for doing so is that once you finish the SWF file, with all the ActionScript code that you are going to add, you will have a completely dynamic game at your disposal. You won’t have to edit the .fla file anymore and re-export it as a .swf. If you ever want to change the topic of the game (the type of word to be guessed) and the words, all you will have to do is edit the text and XML files, upload them to your website, and that’s it! That’s a much, much better solution than cementing the values inside the Flash file and having to re-edit it every time you want to have a different game.

Suppose that you want the player to guess the name of an animal. The welcome message would be as follows: "Welcome to the hangman game! To, win you must try to guess the name of an animal. Press the play button below to start." The two bolded words, “an animal”, are placed in the guessword.txt file that you have downloaded at the beginning of this tutorial. Why both the article and the noun, and not just “animal”?

Well, suppose that you are going to change the game so that the player has to guess the name of a city. If you had put the article “an” into the code of your .FLA file, the resulting message would be “…guess the name of an city”, which is bad English. So it is logical that both the type of word to be guessed an its article should be put in the external text file. Thanks to this, you can just change “an animal” into “a city”.

And now comes the chunk of code that loads the text file and performs different actions, depending on whether the external text file was loaded successfully or not. The first line creates a new LoadVars object, which is used to load external variables into Flash or export variables to an external source:

var guessTopic:LoadVars = new LoadVars();

Like with the majority of objects in Flash, you can’t create them separately, like this: new LoadVars(). This won’t work at all. You must create a variable (guessTopic in this case) and then store an instance of the object that you wish to use inside that variable, exactly like is shown in the line of code above. Since you are creating a new LoadVars object, the type of the guessTopic variable is set to LoadVars, of course (guessTopic:LoadVars). Once you do that, for all practical purposes, you can say that the guessTopic variable is in fact an instance of the LoadVars object.

Let me show you now how to load variables from an external source (the guessword.txt file in this case) using the LoadVars object that you just created. Before loading the actual data, it is considered the best practice to tell Flash first what to do once the loading has finished, and then order it to load the data.

To do this, you must use the onLoad event handler of the LoadVars object.

guessTopic.onLoad = function(success:Boolean) {
if (success) {
startScreen_mc.message_txt.text = welcomePart1+this.myTopic+welcomePart2;
} else {
startScreen_mc.message_txt.text = "The data failed to load. I am sorry!";
}
};
guessTopic.load("guessword.txt");

In ActionScript, an event handler is a function that is called and executed automatically when a particular event occurs. An event is something that happens in your movie: the user clicking a button, a sound finishing playing, the mouse being moved and so on. By inserting event handlers into your code, you enable Flash to react when an event has transpired — you tell it what to do.

So, the onLoad event handler reacts when external variables (variables stored in guessword.txt file in this particular case) have been converted into object properties. To better understand this, have a look at the guessword.txt file. Open it and look at its contents. You will see this:

myTopic=an+animal

myTopic is the name of the variable, and an+animal is its value. You have certainly noticed the plus (+) sign between these two words. It is used to denote spaces in a file that is going to be loaded via the LoadVars object. You can’t just put a simple space between the value’s words, you must separate them with a plus sign.

If you are going to create a project where you will need multiple variables with different values, your text file’s contents would look like this:

myName=John&mySurname=Smith&myAddress=Flash+plaza&myCity=Flashville&myCountry=Flashia

As you can see, the various variables with their respective values are separated by ampersand signs (&). In programmer’s jargon, these variables and their values are called name/value pairs.

I mentioned above that once loaded, these external variables will be converted into object properties. What this means is that the myTopic variable will become a property of the guessTopic LoadVars object. Thanks to that, you can retrieve the value of this variable by referencing it like this: guessTopic.myTopic. And from that, Flash would read the value, which “an animal” in this case.

Fine! Now that you understand how the LoadVars object loads external variables into Flash, let me show you how it will react once the data has been loaded. As you can see, the first line calls the guessTopic object’s onLoad event handler, with a parameter passed to it: success. This parameter is of the Boolean type, meaning that its value can be either true or false.

guessTopic.onLoad = function(success:Boolean) {
if (success) {
startScreen_mc.message_txt.text = welcomePart1+this.myTopic+welcomePart2;
} else {
startScreen_mc.message_txt.text = "The data failed to load. I am sorry!";
}
};

This parameter is necessary, because you must check if the variables have been loaded and converted into properties of the guessTopic LoadVars object. The contents of the event handler function do just that (they are located between the function’s curly braces: { and }). Here, the contents consist of an if/else conditional statement.

If the value of success turns out to be true (meaning the data has been loaded and converted successfully), the welcome message will be displayed. If it turns out as false, an error message will be displayed. In both cases, the message will be displayed in the message_txt text field, which is situated inside the startScreen_mc movie clip. In the first case (when success equals true), the message will be composed of three variables’ values:

welcomePart1+this.myTopic+welcomePart2

You have already defined and seen the values of the variables welcomePart1 and welcomePart2. The middle one is reffered to as this.myTopic. The keyword this points to the guessTopic object itself, because it is written inside the object’s onLoad event handler function. And, just as I said previously, the myTopic property is the variable that has been loaded from the external text file and converted into a property of the guessTopic object. Its value: “an animal”. Without the quotation marks, of course — I have written them here to better distinguisg the value from the surrounding text. So the welcome message will inform the player what is the topic of the game (an animal, a city, a car, etc).

And if the loading fails, the “I’m so sorry” message is displayed :). If the loading fails, it is basically beyond your control. The loading error could be due to the problems the player may have with his Internet connection, his firewall and so on. The best thing that you can do is to notify the player that the loading has failed.

The one thing that you must pay attention to is to place the text file (guessword.txt) in the same folder on your website where the final SWF file (the hangman game Flash movie) is going to be. Also, make sure that the HTML file — the page inside which the Flash SWF file will be embedded is also in this same folder. The same goes for the XML file.

These files do not necessarily have to be in the same folder — I did it like this for the sake of simplicity. You can even put the files on different web servers if you want to, but some additional steps must be made then for the game to function properly. And I don’t wish to discuss this subject here, because this tutorial would span tens of pages. Instead, I will save that for another tutorial, where the cross-domain file loading policy will be explained in more detail.

Finally comes the line that actually tells Flash to load data from the external text file:

guessTopic.load("guessword.txt");

But… as you may have noticed, there is no preloader here. Why? Because the guessword.txt text file has a size of 17 bytes! Making a preloader for this tiny bit of data makes no sense at all. This file will load instantly even on a prehistoric 14.4 K modem connection!

Top of page

Defining the game variables

56 Place the following code right after the one that you wrote previously:

var words:Array = new Array();
var alphabet:String = "abcdefghijklmnopqrstuvwxyz";
var chosenWord:String = new String();
var displayedText:String = new String();
var playAgain:Boolean = false;

Here, you are defining variables that will be used later. If possible, it is a fine practice that you define as many variables as possible in one place. This makes your code more clean and easy to edit later. Let’s see what will each variable be used for:

  • The words variable is of the Array type, meaning it will store many values. Later, you will write the code that will load the XML, find all the words for the hangman game and put it inside this array.
  • The String (a String value is a text value, remember) variable alphabet holds inside all the letters of the English alphabet. This is necessary for checking if a letter the player has pressed is inside the hidden word or not.
  • The chosenWord variable (a String, too) will hold inside itself a randomly picked word from the words array. This is a must, otherwise the same word would pop up each time, which would render the game useless.
  • The displayedText (again, a String) variable’s value is the text that will be shown in the guessWord_txt text field. This is a piece of text that will consist of correctly guessed letters and dots (or question marks) that fill in for the letters that haven’t been guessed by the player yet.
  • The variable playAgain is of the Boolean type and is set to false. This variable will serve for checking if the player has pressed the play button after finishing the first game (whether she succeeded in guessing the hidden word or not) and subsequently, resetting the guessWord_txt text field to its inital state, with no text at all displayed inside it.

Top of page

Using ActionScript to load XML data into Flash

57 Append this code after the existing one:

var wordsLoader:XML = new XML();
wordsLoader.ignoreWhite = true;
wordsLoader.onLoad = function(success) {
if (success) {
parseWords();
} else {
guessWord_txt.text = "Sorry dude, the data just didn’t load.";
}
};
wordsLoader.load("words.xml");

As you can see, this code is similar to the previous one. At first, a new XML object is created (wordsLoader). After that, the XML object’s onLoad event handler function is invoked, to check if the loading succeeded or failed. Like before, this function has inside it an if/else conditional statement. If success turns out as true, the parseWords function is invoked (more on that function later). If not, a “I am sorry” message will be displayed for the user. And after that, the actual XML file gets loaded via the XML object’s load function.

Before I explain you the workings of the XML file, there is one line of code that needs to be explained: the second one, with the ignoreWhite property. The ignoreWhite property of an XML object can be set to either true or false. By defining it as true, you tell Flash to ignore all the white space found in the XML file. Why is this necessary? Because white space in an XML file counts as data! Fine. Now that the above piece of code is clear, let me tell you more about XML.

Top of page

A brief explanation of XML data format and its rules

If you open the file words.xml (which you have downloaded at the start of this tutorial), you will see the following:



dog
elephant
cat
lion
giraffe
wolf
ostrich
penguin
whale
raccoon
tiger
camel
snake
lizard

Before proceeding, you should know that XML stands for EXtensible Markup Language. It is a markup language that describes data. The great thing about the XML data format is that it is platform and operating system independent. This means that an XML file looks exactly the same, whether it is made or read on Linux, Mac, Windows or any other OS or platform. An XML file is basically a text file, with the extension .xml.

When making an XML file, you can use any basic text editor, like Notepad on Windows or SimpleText on a Mac. The important thing to keep in mind is that you should save this file with an .xml extension. Or, you can save it as a .txt file and later change the extension to .xml in your File Explorer.

An XML file can not do anything by itself — it is parsed (read, combed through, looked at) by various programs, browsers, server-side scripts (PHP, Java…) etc if they are enabled to do so. So, you can think of it as a very simple database — stored information.

Unlike an HTML file, where tags are predefined (

, ,

etc), you are the one who defines the tags in an XML file. This means that you can call your tags any way you like, for example: , , etc. But, there are some rules that must be followed. These are really simple, but very, very strict. You must abide by them. Here they are:

  • Each XML file must begin with the XML declaration:

This line tells the parser that it’s, well, an XML file. This is not a tag, but just a declaration. So it appears only once, at the beginning of the XML file. Inside it, the version of XML is stated. Also, the character encoding of the file can be included, like this, for example:

Since the XML file used in this tutorial is written in English, that additional parameter is not necessary.

  • While being composed of different elements, all XML files can contain only one root element. In this example, the root element is . Between the opening and closing tags of the root element, every other element is included. Nothing can be placed outside it:


dog
snake

lizard

Note: I have named each tag within the root element as “word” on purpose (you will see why later). For example, an XML file like this one would be perfectly valid too:


windows
intel
expensive

  • Each element must have a closing tag (except the declaration). So, the following example would result in an error and the XML file couldn’t be parsed:


dog
snake
lizard

  • The XML tags are case-sensitive. The opening and closing tags of a node must be exactly the same. Following this rule, this would be ok:

dog

…while this would cause an error:

dog

  • All the elements of an XML file must be nested correctly. This is an example of proper nesting:


monday
Another week, another monday

…while this one is wrong:


monday
Another week, another monday

Here’s another example. This would be fine:

rose

…and this would result in an error:

rose

  • Any attribute values must be included within quotation marks. A good example of this would be:

Another day at work

…while this is incorrect:

Another day at work

Also, remember that you can insert as many attributes as you need.

These were the rules for writing proper XML. As you saw, they are really simple. You just have to respect them.

One more thing: as I said before, the white space in an XML file counts as data. That’s why you had to set the ignoreWhite property to true in your ActionScript code previously. This can be circumvented with another method, namely, to leave no spaces between your elements, like this:

dogsnakelizard

But this is really hard to read and edit. It is much better to put each element of your XML file on its separate line and use the ignoreWhite property.

Cool! Now that you know the XML rules, I will explain you how Flash parses the XML data.

Top of page

How Flash parses the XML data

58 Add this ActionScript code after all the existing one:

function parseWords():Void {
if (wordsLoader.firstChild.nodeName == "gamedata") {
var rootNode:XMLNode = wordsLoader.firstChild;
for (i=0; i
if (rootNode.childNodes[i].nodeName == "word") {
var currentWord:String = rootNode.childNodes[i].firstChild.nodeValue.toString();
words.push(currentWord);
}
}
}
}

As I mentioned before, the parseWords function will be called upon once the XML data has been successfully loaded. The first line inside this function is a conditional if statement:

if (wordsLoader.firstChild.nodeName == "gamedata") {

…which checks to see if the first child of the wordsLoader XML object is named (nodeName) “gamedata”. The first child of the wordsLoader XML object is indeed named “gamedata”. On the previous page, I have shown you that an XML file can contain only one root node. The root node is the first child (the first element in the XML file’s hierarchy) of the XML object. In this case, the root node is .

So, there is no need for an if/else conditional statement — an if condition will do, because Flash will read it and see that it evaluates as true. So, it will perform all the code within the conditional statement’s curly brackets:

var rootNode:XMLNode = wordsLoader.firstChild;
for (i=0; i if (rootNode.childNodes[i].nodeName == "word") {
var currentWord:String = rootNode.childNodes[i].firstChild.nodeValue.toString();
words.push(currentWord);
}
}

The first line creates the variable rootNode, which is of the XMLNode type. This variable is created just so that you don’t have to write wordsLoader.firstChild each time (remember, firstChild is the gamedata root node in this lesson’s example). It is merely a shorthand name.

And then the for loop begins, which is used to read all the words that will be used in the game and store them in an array:

for (i=0; i if (rootNode.childNodes[i].nodeName == "word") {
var currentWord:String = rootNode.childNodes[i].firstChild.nodeValue.toString();
words.push(currentWord);
}
}

This loop starts with the variable i set to 0 (zero). The loop will make iterations (i.e. it will repeat itself) as long as its condition evaluates as true. And it will increase the value of i with each loop (i++). The condition is that i must be lesser than the number of the child nodes of the root node. The number of the child nodes of root node is retrieved by calling upon childNodes’ length property:

i < rootNode.childNodes.length

In this particular example, this means that i must be lesser than 14. Why? Because there are 14 child nodes inside the gamedata node:



dog
elephant
cat
lion
giraffe
wolf
ostrich
penguin
whale
raccoon
tiger
camel
snake
lizard

As you can see, each child node of the root node has the name word. This is used by the if conditional statement contained within the loop:

if (rootNode.childNodes[i].nodeName == "word") {
var currentWord:String = rootNode.childNodes[i].firstChild.nodeValue.toString();
words.push(currentWord);
}

If the name of the current child node equals “word”, the actions inside the if condition will be performed. Of course, Flash replaces the construct [i] with the current loop iteration number (0, 1, 2, 3 etc), so that it can check each child node: the first one, second… until the last one (which is the fourteenth in this case). Since each child node inside the root one really is named “word”, the following two lines will be executed:

var currentWord:String = rootNode.childNodes[i].firstChild.nodeValue.toString();
words.push(currentWord);

A new variable called currentWord is created and it is of the String type (meaning it holds a text value). Inside it, the name of the current child node node will be stored:

rootNode.childNodes[i].firstChild.nodeValue.toString();

As you can see in the ActionScript line above, the toString() method is used to convert the value of the child element of each root node’s child node to a piece of text. Because this is XML data (nodeValue), and not text data, it has to be converted to a String so that you can use it later in the game. If this XML order puzzles you, here’s a nice graph explaining the hierarchy inside the XML object:

The order of elements in an XML object.

Once this value is retrieved and converted to text, it is stored inside the words array (which you created in the first lines of your code):

words.push(currentWord);

The push method inserts an element to the end of an array. Since the array is completely empty at the beginning, the first element will be placed on the first place, the second one after that, etc. So, with each iteration of the loop, a word pulled out from the words.xml file will be placed inside the words array. Nice! And easy, as you can see. All you have to learn to be able to make Flash read data from an XML file is write some conditional statements and a loop and that’s it.

Ok, after Flash has executed this chunk of code, you will have all the words from your XML file at your disposal, neatly stuffed into an array. Let me show you now how you can pull a word at random from this array so that the player has a different word to guess each time she plays the game.

So please jump to the third part of the ActionScript hangman lesson.

Top of page