
Please support lukamaras.com website:
All my tutorials are free, while hosting costs money.
The most viewed tutorials in April:
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.

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:
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");
REMEMBER 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.
IMPORTANT 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!
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:
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.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.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.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.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.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.
If you open the file words.xml (which you have downloaded at the start of this tutorial), you will see the following:
<?xml version="1.0"?>
<gamedata>
<word>dog</word>
<word>elephant</word>
<word>cat</word>
<word>lion</word>
<word>giraffe</word>
<word>wolf</word>
<word>ostrich</word>
<word>penguin</word>
<word>whale</word>
<word>raccoon</word>
<word>tiger</word>
<word>camel</word>
<word>snake</word>
<word>lizard</word>
</gamedata>
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 (<p>, <body>, <h1> 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: <flash>, <mysuperbtag>, <anything> 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:
<?xml version="1.0"?>
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:
<?xml version="1.0" encoding="UTF-8"?>
Since the XML file used in this tutorial is written in English, that additional parameter is not necessary.
<gamedata>
<word>dog</word>
<word>snake</word>
<word>lizard</word>
</gamedata>
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:
<computer>
<operatingsystem>windows</operatingsystem>
<processor>intel</processor>
<price>expensive</price>
</computer>
<gamedata>
<word>dog</word>
<word>snake
<word>lizard</word>
</gamedata>
<word>dog</word>
...while this would cause an error:
<Word>dog</word>
<diary>
<day>monday</day>
<entry>Another week, another monday</entry>
</diary>
...while this one is wrong:
<diary>
<day>monday<entry>
</day>Another week, another monday</entry>
</diary>
Here's another example. This would be fine:
<flowers><best>rose</best></flowers>
...and this would result in an error:
<flowers><best>rose</flowers></best>
<logentry day="monday">Another day at work</logentry>
...while this is incorrect:
<logentry day=monday>Another day at work</logentry>
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:
<gamedata><word>dog</word><word>snake</word><word>lizard</word></gamedata>
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, proceed onto the next page to see how Flash parses the XML data.