Escolar Documentos
Profissional Documentos
Cultura Documentos
Kristian Besley has worked with multimedia for 3 years but has been
doing creative work with computers for much longer. He currently
develops Flash-based material within an educational environment. This
material includes interactive presentations to illustrate how scientific
things work and GUIs/tools allowing web-based content creation with
basic computer skills. He was a contributing author for the seminal
book Flash Math Creativity and many other friends of ED books. In
2002 he launched the world’s first biannual HTML markup–based
TableArt competition. The competition was an unbelievable success.
ONLINE GAMING WITH PHP
AND MYSQL
FLASH MX 2004 GAMES MOST WANTED
So your game is pretty sweet and people are playing it online, but all the effort that they put in is unre-
warded because they can’t show anyone their impressively large score on it. What you need now is some
way to save the players’ names and scores, so they can boast to everyone else who plays it.
You can save user scores and names using a database and some server-side scripting. No, no, wait—don’t
close the book . . . come back! OK, so for most Flash designers the concepts of databases and server-side
scripting are pretty daunting, but the reality is that any fairly successful ActionScripter will be surprisingly
comfortable with it all.
The database will hold all your players’ scores, names, and other information, and the server-side scripting
is the code that will interpret that information and relay it to and from your Flash movie.
In this chapter, we’ll take you from the most basic dynamic task, loading in variables from a simple text file,
to a fully functional database-driven online high-score board. Although you might not know everything
inside out by the end, this chapter will open your eyes to the possibilities and hopefully take away that ini-
tial fear.
We’re going to use PHP as our server-side scripting language and MySQL as our database to help Flash cre-
ate the high-score table. There are other common server-side scripting languages (ColdFusion and ASP, to
name two) and other database options such as Microsoft Access and SQL Server, but the technologies
we’ve chosen here are free.
To save you a little frustration later on, you’ll need to download and install a
few packages. If this concept fills you with dread, remember that once you
have the packages, you’ll never need to download them again. The actual
downloads are listed a little later in this chapter, but you can go ahead and
read the first section without having to worry about these for now.
Beyond XML, JPEG, and MP3 loading, all data loaded into Flash is presented in the form of variables, little
named packages of information that Flash is ready to understand and display.
&name=kristian&website=graphci.com&age=26&
If you’re already familiar with variables (from ActionScript maybe), what you see here is three variables:
name, website, and age. Here’s how it looks in a more traditional and less cryptic form:
name = kristian
website = graphci.com
age = 26
4
ONLINE GAMING WITH PHP AND MYSQL
In its code form, each of these variables is simply separated by an ampersand or & character. If you wanted
to add a fourth random variable and value to the end of the ugly string, it would look like this:
&name=kristian&website=graphci.com&age=26&instrument=guitar&
The way we prefer to see the variables or information with line breaks for
ease of understanding, Flash prefers to see it with ampersands dividing up
the variables. To each his own, but the information is still the same!
Let’s see how it works in practice by loading some variables into Flash from a standard text file. The files
for this exercise are available in the Chapter 9 code download and are called LoadVars01.fla and
my_data.txt.
Feel free to change this information to match your own personal information, but stick with the struc-
ture and variable names you see here.
&name=yourname&website=whatever.com&age=30&
3. Create a new folder somewhere on your hard drive and save the file as my_data.txt. Close the text file.
4. Open Flash and start a new movie. You need to attach some code to the first frame. So, in the Actions
panel, type the following:
This line creates a new instance of the LoadVars object called inputData. This is used as a store for
variable data, and using LoadVars entitles you to make use of the various methods available to it,
specifically for working with dynamic input and output. These methods include load and sendAndLoad,
both of which you’ll use later in this chapter.
5. Before you go ahead and actually load in the variables from the text file, you need to set up actions to
run once the data has loaded. You do this with an onLoad event handler for the inputData LoadVars
instance like so:
inputData.onLoad = function () {
};
5
FLASH MX 2004 GAMES MOST WANTED
6. Now you need to fill up this function with instructions. Insert the following code between the curly
braces so the event and handler look like this:
inputData.onLoad = function () {
trace ("My name is " + inputData.name);
trace ("My website is " + inputData.website);
trace ("My age is " + inputData.age);
};
You could use this within the preceding handler instead of inputData, but
we’re using inputData to show you explicitly how it works and how the
LoadVars instance is used.
The code you’ve added here uses the imported variables name, website, and age. Because you’re load-
ing the variables from the text file into the inputData instance, you reference them in this form:
loadVarsInstance.variablename;
7. The last bit of code to add actually loads in the variables. Add this to the end of your code block:
inputData.load ("my_data.txt");
The load method does what it says on the tin: it loads in the variables from the specified data source.
All variables then retrieved from the load call are stored in the inputData instance and can be used as
seen in the previous trace code.
Remember, because you’re using trace to display into the Output window,
opening the generated SWF on its own won’t achieve anything—you have to
use Control ➤ Test Movie.
So what have you got? Well, Flash has now fetched that data for you from an external source.
If you’re thinking, “Well, I could have just typed that in manually and saved a lot of trouble!” then you need
to get your head around the projected possibilities brought on by this admittedly basic data-loading example.
6
ONLINE GAMING WITH PHP AND MYSQL
With a little work on this file, you could create an easily updateable Flash website—easily updateable
because you just need to amend a tiny text file rather than go through all the tedious bother of opening
the FLA, remembering how you structured it, changing the text, and uploading a new SWF file.
Why not try modifying the LoadVars01.fla file slightly to display the vari-
ables stored in a file called news.txt in dynamic text boxes? Have a try and
then look at the file LoadVars02.fla for the solution.
For anyone scared by the thought of working with a database, it’s worth knowing that many websites just
use text files for updating. It keeps everything simple. However, in slightly more complex cases they use a
server-side technology (such as PHP, ASP, or Perl) to write or amend the text file.
A for loop, for instance, looks the same in the PHP and ActionScript:
Flash ActionScript
PHP
We’ll come clean. We lied a little, didn’t we? Although the structure is the same, variables in PHP have a
slight difference: they’re prefixed with a $ character. Other than this, though, we’re on familiar ground. You
might have also noticed that a PHP comment looks the same as a Flash comment (//). PHP code lines also
end with a semicolon (;). See? It’s just like ActionScript!
Before we get too far into PHP, let’s continue the introductions with MySQL.
7
FLASH MX 2004 GAMES MOST WANTED
Structured Query Language (SQL) databases allow you to run requests (called queries) on the database.
These requests are written in code form and look something like this:
This particular request will insert a new record into the highscore database table, with the player name
Jim and a reasonable score of 3200. Besides inserting records, select queries can also be run to get infor-
mation from the database. This query will retrieve Jim’s score from the database:
If the previous queries looked a little scarier than PHP, don’t panic just yet. Some nice folks have invented
a graphic interface to help us with all this and to save us from learning the intricacies of yet another lan-
guage. The savior is called phpMyAdmin and it’s run through a plain old browser, making it both PC and
Mac compatible.
Many online hosts who support PHP and MySQL web hosting allow you to
manage your databases online securely using phpMyAdmin.
8
ONLINE GAMING WITH PHP AND MYSQL
Because there are only so many pages in this chapter, we can’t go through all
the required installation procedures for phpMyAdmin, PHP, and MySQL;
instead, you can find some guidance on downloading and setting these up at
the friends of ED community forums: www.friendsofed.com/forums. There
are also plenty of online resources, such as the FoxServ Project
(www.foxserv.net/portal.php), an all-in-one download that will install
PHP, MySQL, and a testing server for you.
Even if you’re not sure if this is all for you, why not read on anyway? Once you
see how easy it is to use PHP and MySQL to create some hot movies, you’ll be
off to php.net in a flash!
Add a new score (this will require two bits of information: the player name and the player’s score)
Show the high scores (you’ll limit the number of displayed scores to ten—nobody is interested in
the underachievers below that!)
9
FLASH MX 2004 GAMES MOST WANTED
2. Beneath the MySQL header in the right pane, type mostwanted into the Create new database text field.
Then click Create.
This will create a brand-new database for you to work with for this exercise and the rest of the chapter.
If you’re working online and your web host provides you with a ready-made
database, you’ll be just fine with the one already set up. In this case, select
the existing database and skip to step 4.
3. After a little while, the page will refresh and the drop-down in the left frame will show the mostwanted
database. Select it from the drop-down to load it into the left pane.
4. In the Name text field in the right frame, type highscore. Type 2 in the Fields text field.
10
ONLINE GAMING WITH PHP AND MYSQL
In MySQL, databases can consist of one or more tables. These actually store the information that you
require. The database is a container for all of the separate tables.
Even though we won’t cover it here, you can use these tables to work
together to store and retrieve different data (such as a table of user-based
data and book data for a book sales website). This is better known as a rela-
tional database system. You don’t need to know this for the exercise ahead,
but it’s nice to know all these tidbits, even just for impressing new friends.
For this exercise, one table with two fields is all you need to store. Click Go to confirm this action. The
next page might appear very sinister at first, and this is healthy! You probably already know that a table
consists of fields, but you probably weren’t aware that each field has to be defined by type, length, and
other considerations.
The reason that MySQL likes the fields typed is so that it can be as efficient or correct as possible. For
instance, MySQL needs to know if a field is a string or a numeric, and how long the field should be. The
latter is specifically in the interest of keeping a well-oiled and speedy database.
Remember the panic of Y2K? One of the major causes of this was that the
year field of databases was set to store two characters rather than the obvi-
ous four. The reason this was done was to store a little less information (two
characters per record to be precise, or 2 bytes!) and keep the database run-
ning a little leaner and speedier.
5. Type score into the first field, and select INT from the Type drop-down. Enter 10 in the Length/Values
field. Leave all the other options as they are.
6. In the second row, type player for the Field field, select VARCHAR for the Type, and add 10 again in
the Length/Values column.
11
FLASH MX 2004 GAMES MOST WANTED
So what happened here? Well, you’re creating two rows for this table, score and player, and each row
is being typed appropriately to the information it will store.
The score field was set to INT (short for “integer”), specifying it as a numeric field, whereas player was
set to VARCHAR (a variable-length string). We’re not going to go into any specifics about all the field
types available, because there are extensive pros and cons for each of them. For this simple task here,
we’re being quite generous with the field lengths, and we’re not giving much consideration to database
optimization or speed. The length of both fields as you can see is here limited to a nice round ten
characters.
7. Now click Save to create the table. The page should refresh and present you with the following:
The first thing to point out is that the table is presented in the left pane, shown in the mostwanted
database (or whatever yours is called). Second, phpMyAdmin reports that the table highscore has been
created, showing that your actions were successful. Beneath this, phpMyAdmin shows you the query that
it ran for you to create the table. Remember that phpMyAdmin is simply a front-end and is creating all
the SQL queries for you (a bit like Dreamweaver producing HTML for you under the hood).
Beneath all the menu options is a visual display of the table structure with a number of available
Actions. The Change option here is most useful, as it allows you to change the structure of the table if
need be.
8. For now, though, click the Insert tab in the right pane. This will allow you to insert a record (or row)
into the database.
12
ONLINE GAMING WITH PHP AND MYSQL
9. In the Value text field of the score field, enter 3200. In the player Value field, type Jim.
10. Then click Go. Once the action is complete, the page will look like this:
13
FLASH MX 2004 GAMES MOST WANTED
For now, you don’t need to worry about the section that appears beneath
what’s pictured.
Most of this looks just like before, except that the Row Statistic area shows one row of data—this is the
record you just added! phpMyAdmin has also created the SQL query for you again (does it ring any
bells?). The query that you’ve just run is one we showed you a little earlier.
12. Click Insert again and add a record with 6000 as the score and your name in the player field. Then
click Go.
As before, this inserts a record into the table with the score of 6000 and your name.
14
ONLINE GAMING WITH PHP AND MYSQL
The SELECT command retrieves data from a table. It can require a number of parameters, but here it
simply relies on three: SELECT, FROM, and LIMIT.
SELECT *: This command requests records from the table. As most of you will be aware, the * charac-
ter is used as a wild card. Because it’s used alone here, this means all records are selected.
FROM: This command simply tells MySQL which table to get the results from. In this case, it is your
new table, highscore.
LIMIT: This command allows you to return only a select number of records. The first number repre-
sents the record number to start from, and the second one specifies the number of records to show.
This query then is providing you with a slight overkill because it’s requesting 30 records and you only
have two. Ho-hum, let’s see how to only fetch one record:
15. Delete the current text in the query box and type the following exactly as shown:
SELECT * FROM 'highscore' LIMIT 0,1;
Even though single quote characters aren’t usually required for table and
row names in MySQL queries, phpMyAdmin likes to have them.
This query asks MySQL to return one record starting from the first (0). Click Go to run the query.
15
FLASH MX 2004 GAMES MOST WANTED
Before you get down to PHP coding, you’ll create the Flash interface.
16
ONLINE GAMING WITH PHP AND MYSQL
stop();
addButton.onRelease = function() {
_root.gotoAndStop(2);
};
6. Insert a new layer called pages between the two layers you already have and, on frame 2, click through
Insert ➤ Timeline ➤ Blank Keyframe.
7. On this keyframe, insert two text fields, and in the Property inspector, set them to Static Text. Type
PLAYER NAME: into one text field and SCORE: into the other. Arrange them vertically, roughly in the cen-
ter of the stage.
10. On the same layer, create another basic button with the text
SUBMIT. Give this an instance name of submitButton.
11. Give the page a title with a static text field reading Add Score.
12. Insert a new layer called status text and place a dynamic text
field with an instance name of statusText. This should be
long and deep enough to show two lines.
17
FLASH MX 2004 GAMES MOST WANTED
stop();
submitButton.onRelease = function() {
sendData = new LoadVars();
sendData.playerOutput = _root.playerInput.text;
sendData.scoreOutput = _root.scoreInput.text;
This code sets up some of the actions for the submitButton. First, as before, you set up an instance of
the LoadVars object called sendData to store the variables that are sent and received to PHP. The val-
ues inputted in the input text fields are then retrieved and set as variables within the sendData
instance.
Out of politeness (or usability, in the current parlance), the statusText box is changed, asking the user
to wait a little while.
As in the earlier exercise, an onLoad event handler is created for the LoadVars object. This event han-
dler is triggered when the processing with PHP is complete. The actual processes that happen in this
callback all depend on what was returned by PHP.
At this point, Flash checks if the result property of the sendData instance is equal to “added”. If it is,
a Player Score Added report is given and the input text boxes are cleared. If the result is anything
other than added, this means that something has gone amiss in the PHP code, in which case the result
is returned as something else. If you’re getting fuddled, don’t worry—this will all come into alignment
in your brain when you see the PHP code in a moment.
15. Insert this last bit of code to complete the actions for the Submit button:
sendData.sendAndLoad("insertScore.php");
};
So what happens when you call the method? First, the variables stored in the LoadVars instance are sent
out to be used by the insertScore.php file. Then PHP processes the file (with or without involvement of a
database) and returns some variables back to Flash. These variables are stored in the instance specified as
the second parameter, in this case sendData.
18
ONLINE GAMING WITH PHP AND MYSQL
You might consider having two instances of the LoadVars object, one for out-
put and one for input. This all depends on your particular project and its
complexity.
OK, now that you’re done with Flash for a moment, save the file as highscores.fla somewhere safe. You’ll
return to it in a moment.
This diagram carefully steps through the whole process, starting with Flash sending the LoadVars data out
to the PHP document and ending with PHP returning some variables back to Flash. So far, you’ve fully pro-
grammed in both the Flash steps (the sending and receiving). Next is the PHP file.
This declares the file as a PHP file. The browser now knows that the code to follow is to be parsed as PHP.
This section of code specifies some much-needed user and database information. As we pointed out
earlier, PHP variables are prefixed with a $ symbol.
19
FLASH MX 2004 GAMES MOST WANTED
It’s worth noting that to be able to access the variables sent from Flash in
the short form demonstrated in this chapter’s PHP files, you’ll need to have
register_globals set to “On” in your php.ini file. You can access variables
in the long form through the $HTTP_POST_VARS associate array. For instance,
if the long form of your variable is $HTTP_POST_VARS['myVariable'), then
the short form of this variable is simply $myVariable.
These variables are required for connection to MySQL. Where relevant, enter your details. The user-
name and password here relate to MySQL and should not be confused with your FTP details.
Your username and password for MySQL should have been the last step
following its installation. If your site is hosted externally, you might need to
contact your host’s admin for the correct details.
$dbhost = "localhost";
$dbusername = "root";
$dbuserpassword = "crazyhorses";
$dbname = "mostwanted";
if (!$link) {
echo "&result=noconnection";
} else {
mysql_select_db($dbname);
}
This code connects to the database using the predefined variables. A handle, $link, is set to the
mysql_connect method, which opens up a connection to the database.
The conditional following this checks to see if the connection was successful. In the first instance, if
$link is false—that is, if the connection was unsuccessful—you use the echo command to send a vari-
able to Flash. The echo command is probably the most common PHP command that Flash scripters will
use, because it’s the most common way of sending information back to Flash.
20
ONLINE GAMING WITH PHP AND MYSQL
You can also use the echo method to write HTML, XML, and other formats to
the browser. The following code, for example, would produce a very simple
HTML page:
<?php
// A simple HTML page to say Hello!
echo "<HTML><HEAD>";
echo "<TITLE>A greeting to the people of Earth</TITLE>";
echo "</HEAD><BODY>";
echo "Hello World!";
echo "</BODY></HTML>";
?>
The usage echo "&result=noconnection"; sends a variable called result with the value of nocon-
nection to Flash. If you remember a conditional in the Flash code earlier on,
sendData.onLoad = function() {
if (sendData.result == "added") {
statusText.text = "Player Score Added.";
_root.playerInput.text = "";
_root.scoreInput.text = "";
} else {
statusText.text = "Error adding score.";
}
};
the result variable is used to check if the record was inserted successfully. The result variable, of
course, is exported from PHP and is imported into the sendData instance. If result isn’t equal to
"added", an error is reported.
4. This next bit of code is test data to check if the PHP file is working correctly. Add this to the code:
// start of temporary data //
$scoreOutput = 1500;
$playerOutput = "Eric";
21
FLASH MX 2004 GAMES MOST WANTED
5. Now you need to create the SQL query in PHP. Add this code:
$query = "INSERT INTO highscore (score, player) VALUES
➥('$scoreOutput', '$playerOutput');";
Because PHP and MySQL are such good pals, you can write queries in PHP and send them directly to
MySQL without much fuss. This line of code creates a string query using the variables $scoreOutput
and $playerOutput.
The actual query here isn’t really that tricky because you’ve already seen this when you entered Jim
with his mighty score of 3200 earlier in the chapter. In this case, though, you’re using variables instead
of hard values.
If some of you are a little dumbfounded by how the variables are included in the quote marks for the
string, this is because PHP can do this without breaking a sweat, simply because PHP variables are dis-
tinguished by the $ character. This means that variables can be contained within a string and are
replaced with their true value.
Given that name is equal to “Richard”, the greeting variable in both instances would read “Hello there
Richard!”
?>
The mysql_query command runs the query passed as an argument to it, in this case the $query vari-
able. If the operation is successful, the result variable is echoed as added; if the operation was a failure,
result is exported as notadded.
7. Save the file as insertScore.php in a new folder called mostwanted within your web sharing or web
root folder, and then close it.
22
ONLINE GAMING WITH PHP AND MYSQL
The simple reason you’ve opened the file here is to test the temporary variables that you inserted
within the file. If you see what is shown in the previous image, this means that connection to the data-
base was successful, and the record was inserted. In the event of something other than what you see
in the previous image, you’ll need to do a little troubleshooting.
If result is equal to noconnection, then the connection to the database is unsuccessful—check that the
database and user information is correct.
If result is notadded, then chances are your query was written incorrectly. Although queries enable you
to easily talk to MySQL, they’re very strict on their structure and syntax, so you need to be careful.
If you didn’t even see result and the browser is full of garble, then you’ve typed something incorrectly
and the PHP file couldn’t be parsed because of bad syntax. In this case, check the code strictly, or copy
the file insertScore.php, which is available with this chapter’s source code.
10. You should see the new added record with Eric’s
name and frightfully low score. This proves that
the PHP file and database are talking to each
other. Keep phpMyAdmin open for now. Now
you’ll test if Flash interacts with the two.
//$scoreOutput = 1500;
//$playerOutput = "Eric";
23
FLASH MX 2004 GAMES MOST WANTED
15. Type in a name and score, and click the SUBMIT button. After a little while, the data will be added and
the text boxes cleared:
Otherwise, your high-score table is half done. So far, you can save
the scores, but you’re unable (without phpMyAdmin) to view the
scores. All that remains to do to make this fully functional is finish
the Flash file and write a new PHP file. To give you a break from
PHP, you’ll finish the Flash file first.
24
ONLINE GAMING WITH PHP AND MYSQL
4. Insert a blank keyframe on frame 3 of the actions layer. Attach the following code to it:
stop();
loadData = new LoadVars();
statusText.text = "Loading scoreboard.\nPlease wait.";
loadData.onLoad = function() {
if (loadData.result == "okay") {
statusText.text = "";
So far this code should all be familiar. The LoadVars instance here is called loadData, and as before, an
onLoad event is set up. In the event of a successful action, you proceed to draw the leaderboard.
The basic premise behind the table drawing is to fill each column with its own relevant data, adding a
newline character (\n) after each piece of data. The loop here is set to run according to the value of
loadData.rows, a variable accounting for the number of score records returned from PHP.
The next three lines actually write into the dynamic text fields using += to add to their current value.
Square brackets are used to allow dynamic referencing because the variables will be returned with a
suffixed figure (for example, player2, score5). More on this when you see the PHP file.
Most of this code should be familiar to you by now, so we’ll save our breath. The last thing to do in this
Flash file is add the code for the Show Scores button.
Note that the random integer query string added to the filename in the
load() call is in place to prevent the browser from caching the PHP page.
Using a random number (up to a million) ensures that each call of the PHP
script is likely to be unique and fresh. Without this appendage, the browser is
likely to cache the page and potentially show the same results as previous
calls to it.
25
FLASH MX 2004 GAMES MOST WANTED
7. Select frame 1 of the actions layer and open the Actions panel. Add the following new code (highlighted):
stop();
addButton.onRelease = function() {
_root.gotoAndStop(2);
};
showButton.onRelease = function() {
gotoAndStop(3);
};
8. Now save the file and republish it. Before you can run it, you need to create the showScores.php file.
$dbhost = "localhost";
$dbusername = "root";
$dbuserpassword = "badger";
$dbname = "mostwanted";
if (!$link) {
echo "&result=noconnection";
} else {
mysql_select_db($dbname);
}
2. Now add this:
$query = "SELECT * FROM highscore ORDER BY score DESC LIMIT 0,
➥10;";
$result = mysql_query ($query);
As before, you create a query string, this time using SELECT to fetch records from the database. This
query is basically saying this:
“SELECT all fields FROM highscore and ORDER the results according to the score field. Display the
results in DESCending order and LIMIT the results to 10 rows, starting from record 0.”
The next line of code sets a handler ($result) for the query. The handler will be used in a moment to
extract the data. This $result isn’t to be confused with the result variable that you export later.
26
ONLINE GAMING WITH PHP AND MYSQL
First, you initiate the $count variable. You’ll see how this is used in a moment. On the next line, the
while structure is set up. The mysql_fetch_array command is used here to extract a row of data as an
array. The current row or array then is stored in $query_data. The while loop here will run as long as
there are rows to extract from $result.
The next two lines set the variables $player and $score to values extracted from the current row
array. The values are extracted using what are called associative arrays. As well as the standard numeric
array type (for example, array[1]), PHP can also use string-based associative arrays (for example,
array["name"]) for storage.
The beauty of using them here, rather than using numeric arrays, is that you can reference the field of
the record directly. For those of you unable to come to terms with this array type, you’ll be glad to
know that you can use numeric arrays instead (although you’ll have to remember your table structure),
counting the fields from the left (0) and up. The last two lines then will look like this:
$count++;
}
Good old echo is used here to send the values from $player and $count out to Flash. As mentioned
earlier, the variables are exported with a suffixed number to the variable names. Say $count is 3 and
$score is 2000, the line
echo "&score$count=$score";
&score3=2000
?>
This sends the result variable as normal and also the number of rows reported. The latter is used in
Flash in the eventuality that there are less than ten scores in the table.
6. Save this file in the same location as the others, and name it showScores.php.
27
FLASH MX 2004 GAMES MOST WANTED
7. Now open the showScores.php file in your browser. The variables are presented in a familiar ugly
stream:
Even though this presentation is ugly, it’s also good because it proves that the query worked. If you
carefully look at the scores from left to right, they should be in descending order from highest to low-
est. As normal, if something has gone wrong, check your PHP code. The final action for this exercise is
to check that Flash is playing ball with your PHP file.
highscore.fla
highscore.swf
highscore.html
insertScore.php
showScores.php
Additionally, the SQL queries in this section are available in the sql queries folder of the source code:
highscore_table.sql
highscore_data.sql
highscore_tbl+data.sql
insert_example.sql
select_example.sql
select_limit0_1.sql
OK, now you can see that you’ve created a fully functional high-score table that will work online, out of
the box.
For this I’ve used my previous FLA code as a base, stitched this onto Keith’s code, and used
showScores.php and insertScore.php just as they already are. I’ve even used the same database and table.
The file is water_final_scores.fla. I recommend you open it, and I’ll show you where exactly I made the
changes.
First, because the game only allowed the user to play one game, I had to allow the user to restart. Some of
the original code then was encapsulated into a function called start. The following code in bold is new or
added:
function start() {
_root.hs.removeMovieClip();
score = 0;
score_txt.text = score;
nextBonus = 1000;
// start spraying
start_btn.onPress = function() {
squirtInt = setInterval(squirt, 50);
};
// stop spraying
start_btn.onRelease = start_btn.onReleaseOutside = function() {
clearInterval(squirtInt);
};
status_txt.text = "";
waterTank_mc.gauge_mc.waterLevel_mc._yscale = 100;
flame_mc.reset();
};
The start function is then called at the very end of the code. Next, I had to add some code to run upon
game over:
function squirt() {
// make a drop of water
var drop_mc = attachMovie("drop", "d"+depth, depth++);
// vary its size
drop_mc._xscale = drop_mc._yscale=125+Math.sin(dropSize += .9)*50;
// position it at end of nozzle
drop_mc._x = nozzle_mc._x+5;
drop_mc._y = nozzle_mc._y;
// give it some speed
drop_mc.vx = 10;
drop_mc.vy = Math.random()-.5;
// assign enterFrame handler
drop_mc.onEnterFrame = move;
// reduce water level
waterLevel -= .1;
// adjust gauge
waterTank_mc.gauge_mc.waterLevel_mc._yscale = waterLevel;
// check if water is gone
29
FLASH MX 2004 GAMES MOST WANTED
if (waterLevel<=0) {
// disable button
delete start_btn.onPress;
// stop spraying
clearInterval(squirtInt);
status_txt.text = "Game Over!";
onGameOver();
}
}
sendData.onLoad = function() {
if (sendData.result == "added") {
hs.statusText.text = "Player Score Added.";
hs.playerInput.text = "";
hs.scoreInput.text = "";
} else {
statusText.text = "Error adding score.";
}
status_txt.text = "";
getHighScores();
};
Let’s look at what’s happening here. First, a newly added movie clip called highscore page (located in the
high score assets folder) is attached from the Library. This movie clip contains two frames (as in previous
example): one for adding a player’s score and the other for displaying the high scores. Take a look.
This is then sent to frame 1, the adding page. The player (regardless of her score) is invited to add her
name as before. This time her score is set as the score variable from the game. This prevents the user from
cheating and entering her own score.
30
ONLINE GAMING WITH PHP AND MYSQL
The rest of the code here mimics the previous FLA, with the exception of the getHighScores function call
at the end of the onLoad handler. That function is coming right up.
Unlike in the previous FLA, in which you requested the high-score table, this time it’s automatically shown
after the player enters his name. The only difference here is how the table is displayed, using a single cen-
tered dynamic text field (scoresTxt):
31
FLASH MX 2004 GAMES MOST WANTED
The Play Again button then launches the start function to reset the score, remove the score page
(_root.hs.removeMovieClip();), and start the flame afresh.
As you can see here, there isn’t much that I’ve changed in the original game file—much of the code is just
tweaking to make the game run from the start again. The actual saving and retrieving code is only a little
different, and better still, I’ve made no changes to the database or PHP files!
When you come to run this version of the game, remember that you’ll need to launch it in a browser from
a web server URL. The game’s HTML and SWF files should also be in the same folder as the PHP files for it
all to work.
You can find all the files for this tutorial with this chapter’s example downloads, in the water folder:
water_score_final.html
water_score_final.swf
water_score_final.fla
insertScore.php
showScores.php
This high-score table is pretty successful and quite fast. However, the one disadvantage of it is that every
score is entered into the database. If you imagine some hard-core gamer whiling away most of his hours
(when he should be working) playing this, the database can quickly become overcrowded.
The simple way around this is to check the score is worthy of a placement in the leaderboard before
adding it. If the score is high enough for, say, the top 100, add it to the database; if it’s lower than the top
100, reject it. The best way to do this would be to check the score against the database scores at the end
of the game. We’re not going to cover that here, but with a little research it should be within your grasp
very soon.
32
ONLINE GAMING WITH PHP AND MYSQL
Lollipop Break
If you’ve made it this far, reward yourself with a lollipop—you’ve done very well. We didn’t say it would be
easy, and it might not have been as fun as some of the earlier chapters, but the important thing is that
you’ve made the leap from Flash designer to Flash developer in a small number of pages.
As we pointed out before you started, the purpose of this chapter isn’t to teach you PHP and MySQL from
scratch, but to try to get you working with them and also to provide you with a fully functioning high-score
table. For those of you keen to look into using PHP and MySQL with Flash a little more, we recommend a
couple of books from friends of ED: Foundation PHP for Flash and Advanced PHP for Flash will give you a
superb grounding in these technologies. These books, coupled with knowledge of the LoadVars object, will
help you hit the ground running. And it’s worth staying tuned to www.friendsofed.com to hear about new
PHP books.
33
FLASH MX 2004 GAMES MOST WANTED
First, let me point out that the arcade is a little clunky. It’s a huge triangular glass cabinet with plastic hybrid
horse/jockeys models of many bright colors. To re-create the effect in Flash would need a little attention,
but I think the most important aspect to get right is its quirky motion.
The movement of the horses in the cabinet is stunted, jolty, and irregular. To mimic this, I used a very sim-
ilar method, giving each horse the same standard round speed (a round is specified as an interval that
recurs every second) and the random chance of a bonus boost. The total round speed then (from the stan-
dard speed + the bonus distance) is given to the horse to run over a second, producing a very staggered
and nigh-on impossible burst. I did originally try the horses with inertia-based movement, but this was far
too clean for this particular game.
Another idea stolen from the arcade game is the continual racing of the horses. To attract attention, the
horses continually race, allowing only a brief moment to bet on them. To give a similar live feel to it, I went
with the same method, allowing the horses to race without waiting for the player’s permission to race.
Watching other people playing this, I’ve noticed that they tend to impulse bet and are constantly aware of
the clock counting down.
The live game is viewable at www.graphci.com/horse, so you can see how the dynamic files work in prac-
tice. All the required files are available with this chapter’s source code, within the horse folder.
34
ONLINE GAMING WITH PHP AND MYSQL
In the next few sections, I’ll detail the purpose of every one of the PHP files. This knowledge, coupled with
the FLA, should allow you to make something similar in a snap!
Before you look at the individual files, let’s look at the table structure to see what information is stored for
each player:
username: The player’s username data. No two usernames can be the same, so a check is provided to
ensure that a username isn’t already taken (addUser.php).
winnings: The amount of cash in the player’s pocket. This cash is used to bet and for the leaderboard.
bankrupts: The number of times the player has been made bankrupt. This is used to shame the player
on the My Stats screen.
registerdate: The date the user registered as a player. This data is stored as a UNIX timestamp, a date
taken from the server. I’ve limited this to eight characters, so that it reports the date in the following
format: yyyymmdd. Timestamps can report the time as well as date.
35
FLASH MX 2004 GAMES MOST WANTED
<?php
// addUser.php //
// adds a user's details to the database //
include "connect_db.inc.php";
if ($rownums > 0) {
echo "&result=userexists";
} else {
if (mysql_query ($query)) {
echo "&result=added";
} else {
echo "&result=notadded";
}
}
?>
The first bold line here attempts to fetch a record from the database with the username that was entered
in the Flash movie ($userInput). The intention here is to check if the username already exists in the data-
base. The variable $rownums is set to the number of rows of data fetched from the query (using the
mysql_num_rows command).
The final bold line then checks to see if any rows were returned. In the event that none were returned (the
username doesn’t already exist), the user is added to the database.
36
ONLINE GAMING WITH PHP AND MYSQL
The NOW() function here adds the current date to the registerdate field. This fetches the current date
from the UNIX server as opposed to the user’s own machine.
<?php
// loginUser.php //
// login a user //
include "connect_db.inc.php";
if ($rownums > 0) {
$query_data = mysql_fetch_array ($result);
if ($passInput == $query_data["password"]) {
echo "&result=loggedin";
//
$storedMoney = $query_data["winnings"];
echo "&money=$storedMoney";
} else {
echo "&result=wrongpassword";
}
} else {
echo "&result=nouser";
}
?>
This time the query requests the username, password, and winnings from the database. As before
$rownums is used to check if the user exists in the database. If the user doesn’t exist in the database, the
result variable is returned as nouser and Flash returns a suitable error.
If the user exists, the next check required sees if the user has the right password. $passInput, which rep-
resents the inputted password from the Flash text field, is checked against the stored database password
information. If the password is correct, the stored cash is sent to Flash; if the password isn’t correct, result
is returned as wrongpassword. Flash will then report appropriately according to either eventuality.
The default else here refers to the user not existing. Flash is then informed of this. If the user is logged in,
the user is sent to frame 3 to play the game.
37
FLASH MX 2004 GAMES MOST WANTED
I opted then to save the general data after every five races or, of course, on logout. The thisrace variable
in Flash is incremented every race, and when it hits 5, the updateAll.php file is called from Flash. However,
when this is called, the game continues (so the user is unaware and the experience is seamless).
<?php
// updateAll.php //
// update a number of fields in the database //
include "connect_db.inc.php";
// update winnings //
if ($racenum > 0) {
$racequery = "UPDATE horses SET racesrun = racesrun + $racenum
➥WHERE username = '$userdata';";
$runreturned = mysql_query ($racequery);
}
if ($wonraces > 0) {
$wonquery = "UPDATE horses SET raceswon = raceswon + $wonraces
➥WHERE username = '$userdata';";
$wonreturned = mysql_query ($wonquery);
}
?>
You might notice here that the queries look a little different from any you’ve seen before. The UPDATE
command is pretty self-explanatory: it simply allows you to update the values stored in a particular field of
a record. Remember that INSERT is used to write a new record. UPDATE therefore is essential for any main-
tenance on the records.
38
ONLINE GAMING WITH PHP AND MYSQL
<?php
// incrementBankrupt.php //
// add one to bankrupts value /
include "connect_db.inc.php";
if (!$result) {
echo "&result=error";
}
?>
As with the updateAll.php file, the UPDATE command is called, and the value stored in the bankrupts row is
incremented by 1. The value of the bankrupts row is displayed when the user requests her personal statistics.
Racing Form
One of the benefits of storing the user’s data is the ability to recall the
user’s total records at any time. In this game, certain data is kept to
allow a user to review her betting abilities. The values stored in the
raceswon and racesrun rows, for example, are used to calculate a
win/bet ratio.
The bankrupts row is used to shame the player and to calculate the
player’s total money after bank loans. All of the code here is quite
straightforward:
<?php
// getMyStats.php //
// get user's stats //
include "connect_db.inc.php";
39
FLASH MX 2004 GAMES MOST WANTED
echo "&player=$player";
echo "&cash=$cash";
echo "&wins=$wins";
echo "&races=$races";
echo "&startDate=$startDate";
echo "&bankrupts=$bankrupts";
echo "&result=okay";
?>
<?php
// showLeaderboard.php //
// report top 20 players according to score //
include "connect_db.inc.php";
$count = 0;
echo "&result=okay";
40
ONLINE GAMING WITH PHP AND MYSQL
$count++;
}
}
echo "&rows=$count";
?>
<?php
// common_db.inc.php //
// stores mysql dbase login info //
?>
<?php
// connect_db.inc.php //
// login to database //
include "common_db.inc.php";
if (!$link) {
echo "&result=noconnection";
} else {
mysql_select_db($dbname);
}
?>
41
FLASH MX 2004 GAMES MOST WANTED
Summary
It wasn’t possible to go into depth about every aspect of the game here, but I’ve tried to outline some of
the situations and processes involved so you know how to approach a similar project.
From a game point of view, there are many things here that I would like to have done differently given a
little more time. The original game, for instance, was intended to be isometric, with the movement consid-
erations put in place (this might get considered in future, of course). The odds of the horses were also
meant to change according to form and many other variables. I also wanted to make a random horse name
generator.
If you have any suggestions or comments on the game, I’d love to hear them. E-mail them to
horses@graphci.com, and have fun with these files!
42