42

%28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

Embed Size (px)

Citation preview

Page 2: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

Kristian Besley

Kristian Besley has worked with multimedia for 3 years but has beendoing creative work with computers for much longer. He currentlydevelops Flash-based material within an educational environment. Thismaterial includes interactive presentations to illustrate how scientificthings work and GUIs/tools allowing web-based content creation withbasic computer skills. He was a contributing author for the seminalbook Flash Math Creativity and many other friends of ED books. In2002 he launched the world’s first biannual HTML markup–basedTableArt competition. The competition was an unbelievable success.

Page 3: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHPAND MYSQL

Page 4: %28sample%29 Flash MX 2004 Games Most Wanted - 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 someway 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’tclose the book . . . come back! OK, so for most Flash designers the concepts of databases and server-sidescripting are pretty daunting, but the reality is that any fairly successful ActionScripter will be surprisinglycomfortable with it all.

The database will hold all your players’ scores, names, and other information, and the server-side scriptingis 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 everythinginside 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, toname two) and other database options such as Microsoft Access and SQL Server, but the technologieswe’ve chosen here are free.

To save you a little frustration later on, you’ll need to download and install afew packages. If this concept fills you with dread, remember that once youhave the packages, you’ll never need to download them again. The actualdownloads are listed a little later in this chapter, but you can go ahead andread the first section without having to worry about these for now.

Dynamic Information in FlashBefore you start working with any server-side scripting or databases, it’s really worth getting a grasp of howFlash imports data dynamically.

Beyond XML, JPEG, and MP3 loading, all data loaded into Flash is presented in the form of variables, littlenamed packages of information that Flash is ready to understand and display.

You might have seen something as ugly as this before:

&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

Page 5: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

In its code form, each of these variables is simply separated by an ampersand or & character. If you wantedto 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 forease of understanding, Flash prefers to see it with ampersands dividing upthe 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 filesfor this exercise are available in the Chapter 9 code download and are called LoadVars01.fla andmy_data.txt.

Simple Dynamic Exercise

1. Open a standard plain text editor, such as Notepad (Windows), TextEdit (Mac OS X), or SimpleText(Classic Mac). If you prefer (and have) something stronger, such as HomeSite or BBEdit, go ahead anduse it.

2. Type the following into your text editor:

&name=kristian&website=graphci.com&age=26&

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 Actionspanel, type the following:

inputData = new LoadVars ();

This line creates a new instance of the LoadVars object called inputData. This is used as a store forvariable 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 torun once the data has loaded. You do this with an onLoad event handler for the inputData LoadVars

instance like so:

inputData.onLoad = function () {

};

5

Page 6: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

6. Now you need to fill up this function with instructions. Insert the following code between the curlybraces 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, butwe’re using inputData to show you explicitly how it works and how theLoadVars 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 asseen in the previous trace code.

8. Save the Flash file in the same location as themy_data.txt file and run the movie using Control ➤Test Movie. Here’s what the output looks like on aMac:

6

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 touse 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 needto get your head around the projected possibilities brought on by this admittedly basic data-loading example.

Page 7: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

7

With a little work on this file, you could create an easily updateable Flash website—easily updateablebecause you just need to amend a tiny text file rather than go through all the tedious bother of openingthe 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 andthen 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 justuse text files for updating. It keeps everything simple. However, in slightly more complex cases they use aserver-side technology (such as PHP, ASP, or Perl) to write or amend the text file.

Using PHP and MySQLOK, we’re not going to go into text file updating here; rather, we’re going much further up the road andlooking at working with a MySQL database, and we’re going to talk to it with a little PHP. Let’s get the briefintroductions over with and then dig into some practical exercises.

PHP First LookPHP is a free-to-use, open source server-side scripting language used for all manners of tasks, from work-ing with files and folders on a server to updating a database. It’s pretty impossible to cover PHP fromscratch here, but we hope this section will show those of you who fear anything to do with back-end script-ing that it really isn’t a big deal. There are many major advantages to learning PHP for present Flash users—for example, the huge variety of PHP/Flash tutorials online, the gentle learning curve, and the fact thatmuch of the syntax looks similar to ActionScript.

A for loop, for instance, looks the same in the PHP and ActionScript:

Flash ActionScript

for (i=0; i<10; i++) {

// do this

}

PHP

for ($i=0; $i<10; $i++) {

// do this

}

We’ll come clean. We lied a little, didn’t we? Although the structure is the same, variables in PHP have aslight difference: they’re prefixed with a $ character. Other than this, though, we’re on familiar ground. Youmight have also noticed that a PHP comment looks the same as a Flash comment (//). PHP code lines alsoend with a semicolon (;). See? It’s just like ActionScript!

Before we get too far into PHP, let’s continue the introductions with MySQL.

Page 8: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

8

MySQL First LookMySQL is also open source, meaning there’s an open development community and it’s free. In short, it’s apowerful database used online to store and organize all manner of data.

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:

INSERT INTO highscore (score, player) VALUES ('Jim', '3200');

This particular request will insert a new record into the highscore database table, with the player nameJim 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:

SELECT score FROM highscore WHERE player = 'Jim';

If the previous queries looked a little scarier than PHP, don’t panic just yet. Some nice folks have inventeda 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 andMac compatible.

Many online hosts who support PHP and MySQL web hosting allow you tomanage your databases online securely using phpMyAdmin.

Page 9: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

9

Because there are only so many pages in this chapter, we can’t go through allthe required installation procedures for phpMyAdmin, PHP, and MySQL;instead, you can find some guidance on downloading and setting these up atthe friends of ED community forums: www.friendsofed.com/forums. Thereare also plenty of online resources, such as the FoxServ Project(www.foxserv.net/portal.php), an all-in-one download that will installPHP, 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 yousee how easy it is to use PHP and MySQL to create some hot movies, you’ll beoff to php.net in a flash!

Creating a High-Score TableIn this next exercise you’re going to flex some muscles. You’ll create a fully functional MySQL databasehigh-score table. Let’s look at what you need to do:

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 inthe underachievers below that!)

Working with phpMyAdmin

Let’s start by creating a new database and table using your data-churning friend, phpMyAdmin.

1. First, access phpMyAdmin through your browser window: http://127.0.0.1/~username/<phpMyAdminFolder>/index.php

Page 10: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

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.

10

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-madedatabase, you’ll be just fine with the one already set up. In this case, selectthe 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 mostwanteddatabase. 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.

Page 11: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

In MySQL, databases can consist of one or more tables. These actually store the information that yourequire. 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 worktogether to store and retrieve different data (such as a table of user-baseddata 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. Thenext page might appear very sinister at first, and this is healthy! You probably already know that a tableconsists of fields, but you probably weren’t aware that each field has to be defined by type, length, andother considerations.

The reason that MySQL likes the fields typed is so that it can be as efficient or correct as possible. Forinstance, MySQL needs to know if a field is a string or a numeric, and how long the field should be. Thelatter 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 theyear 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 (twocharacters 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/Valuesfield. 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 inthe Length/Values column.

You should now have the following onscreen:

11

Page 12: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

So what happened here? Well, you’re creating two rows for this table, score and player, and each rowis 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 wasset to VARCHAR (a variable-length string). We’re not going to go into any specifics about all the fieldtypes 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 databaseoptimization or speed. The length of both fields as you can see is here limited to a nice round tencharacters.

For more on field types, click the Documentation hyperlink shown inphpMyAdmin.

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 mostwanteddatabase (or whatever yours is called). Second, phpMyAdmin reports that the table highscore has beencreated, showing that your actions were successful. Beneath this, phpMyAdmin shows you the query thatit ran for you to create the table. Remember that phpMyAdmin is simply a front-end and is creating allthe 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 availableActions. The Change option here is most useful, as it allows you to change the structure of the table ifneed 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

Page 13: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

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

Page 14: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

12. Click Insert again and add a record with 6000 as the score and your name in the player field. Thenclick Go.

As before, this inserts a record into the table with the score of 6000 and your name.

13. Now click Browse again to show both records.Big deal, huh?

14

For now, you don’t need to worry about the section that appears beneathwhat’s pictured.

Most of this looks just like before, except that the Row Statistic area shows one row of data—this is therecord you just added! phpMyAdmin has also created the SQL query for you again (does it ring anybells?). The query that you’ve just run is one we showed you a little earlier.

11. One other thing to note is that theBrowse option is now available. Goon, click it. The Browse option pres-ents you with all the records storedin the table. At the moment, thetable is hardly bursting, but Jim canbe sure he’s the highest scoringplayer—for now at least!

Page 15: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

Here’s where you take a look under the hood.OK, even though you just clicked the Browsehyperlink and it showed you a few records, thework for phpMyAdmin is a little more compli-cated—it’s actually running a query for you.Here’s how that query looks:

The SELECT command retrieves data from a table. It can require a number of parameters, but here itsimply 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 yournew 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 onlyhave two. Ho-hum, let’s see how to only fetch one record:

14. Click the SQL tab to bring upthe query box.

In this text field, you can typeyour own queries by hand.Scary!

15

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 androw 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.

Page 16: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

This time as expected, you can see only Jim’s recordbecause MySQL has only returned one record to you.This might not seem that useful now, but later on itwill help you to differentiate between the top tenplayers.

Before you go on to work with Flash and PHP, whoremembers the other query that we showed you ear-lier? No one? Well, don’t bother turning back thepages to find it because we’ll show it to you again.Here it is:

SELECT 'score' FROM 'highscore' WHERE 'player' = 'Jim';

Given what you’ve just seen, do you want to guesswhat this does? Click the SQL option and type it intothe query box to see if you’re right. For those of youwho categorize yourselves as “curious but lazy,”here’s the answer (but you’ll have to turn the bookupside down to see it!):

OK, for now you can close phpMyAdmin and openFlash for the next stage.

Preparing the Flash File

Before you get too excited, you’re not going to dive straight into building a game here—at the end of thischapter you’ll put together everything that you’ve learned and look at a neat horse-racing game. Anyway,we hope the previous chapters in the book have done enough to fuel your imagination and provide youwith tips on game creation and programming. In this section, you’re going to create a Flash interface tocommunicate (via PHP, of course) with the highscore table.

Before you get down to PHP coding, you’ll create the Flash interface.

1. Create a new Flash document and rename Layer 1 buttons.

2. On the buttons layer, create two simple movieclips using the Rectangle tool and place them inthe top corner. Give them text as shown:

3. Extend the buttons layer to frame 3 using F5.

4. Give the buttons instance names of addButton and showButton, respectively.

5. Insert a new layer called actions above the current layer and add the following code to it on frame 1:

16

Page 17: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

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 throughInsert ➤ Timeline ➤ Blank Keyframe.

7. On this keyframe, insert two text fields, and in the Property inspector, set them to Static Text. TypePLAYER NAME: into one text field and SCORE: into the other. Arrange them vertically, roughly in the cen-ter of the stage.

8. Alongside these, place two more text fields, withtheir Properties set to Input Text. Also in theProperty inspector, give them the instance namesof playerInput and scoreInput.

9. Make sure that Show Border Around Text buttonis pressed in, as you can see on the screenshot.Also, ensure the Maximum Characters for eachinput field is set to 10.

The Maximum Characters is set to ten characters to coordinate with themaximum field values set earlier in the database. If you didn’t restrict thisand the user entered more than ten characters, only the first ten would berecorded in the database.

10. On the same layer, create another basic button with the textSUBMIT. 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 textfield with an instance name of statusText. This should belong and deep enough to show two lines.

This text field will be used to report any errors or successesfrom the dynamic fetching and sending of data.

13. Insert a new blank keyframe on frame 2 of the actions layerand add the following code:

17

Page 18: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

stop();

submitButton.onRelease = function() {

sendData = new LoadVars();

sendData.playerOutput = _root.playerInput.text;

sendData.scoreOutput = _root.scoreInput.text;

statusText.text = "Sending Data...\nPlease wait.";

This code sets up some of the actions for the submitButton. First, as before, you set up an instance ofthe 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 sendDatainstance.

Out of politeness (or usability, in the current parlance), the statusText box is changed, asking the userto wait a little while.

14. Now add the following code:

sendData.onLoad = function() {

if (sendData.result == "added") {

statusText.text = "Player Score Added.";

_root.playerInput.text = "";

_root.scoreInput.text = "";

} else {

statusText.text = "Error adding score.";

}

};

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 thiscallback 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 anythingother than added, this means that something has gone amiss in the PHP code, in which case the resultis returned as something else. If you’re getting fuddled, don’t worry—this will all come into alignmentin 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 sentout to be used by the insertScore.php file. Then PHP processes the file (with or without involvement of adatabase) and returns some variables back to Flash. These variables are stored in the instance specified asthe second parameter, in this case sendData.

18

Page 19: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

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 itscomplexity.

OK, now that you’re done with Flash for a moment, save the file as highscores.fla somewhere safe. You’llreturn to it in a moment.

Creating the PHP Code

Now that your Flash file is prepped, you need to create the insertScore.php file to process the variablesand create the MySQL query. Before you get started on this, though, we’d like to review the whole dynamicprocess that you’re undertaking here. Luckily, it can be summed up with a simple diagram:

19

This diagram carefully steps through the whole process, starting with Flash sending the LoadVars data outto 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.

1. Open your favorite text editor and type the following:

<?php

This declares the file as a PHP file. The browser now knows that the code to follow is to be parsed as PHP.

2. Now add the following:

$dbhost = "<enter your hostname here>";

$dbusername = "<enter your MySQL username here>";

$dbuserpassword = "<enter your MySQL password here>";

$dbname = "mostwanted";

This section of code specifies some much-needed user and database information. As we pointed outearlier, PHP variables are prefixed with a $ symbol.

Page 20: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

It’s worth noting that to be able to access the variables sent from Flash inthe short form demonstrated in this chapter’s PHP files, you’ll need to haveregister_globals set to “On” in your php.ini file. You can access variablesin the long form through the $HTTP_POST_VARS associate array. For instance,if the long form of your variable is $HTTP_POST_VARS['myVariable'), thenthe 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 stepfollowing its installation. If your site is hosted externally, you might need tocontact your host’s admin for the correct details.

Here’s an example of how these details might look:

$dbhost = "localhost";

$dbusername = "root";

$dbuserpassword = "crazyhorses";

$dbname = "mostwanted";

3. Add this code:

$link = mysql_connect ($dbhost, $dbusername, $dbuserpassword);

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 themysql_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 willuse, because it’s the most common way of sending information back to Flash.

20

Page 21: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

You can also use the echo method to write HTML, XML, and other formats tothe browser. The following code, for example, would produce a very simpleHTML 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, ofcourse, 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";

// end of temporary data //

These variables mimic the exportedvariables from Flash. Any variablessent from Flash such as scoreOutputand playerOutput are immediatelymade available to PHP for use. Theonly difference, of course, is that thevariables in PHP are prefixed with $.

21

Page 22: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

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 toMySQL without much fuss. This line of code creates a string query using the variables $scoreOutputand $playerOutput.

The actual query here isn’t really that tricky because you’ve already seen this when you entered Jimwith his mighty score of 3200 earlier in the chapter. In this case, though, you’re using variables insteadof hard values.

If some of you are a little dumbfounded by how the variables are included in the quote marks for thestring, 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 arereplaced with their true value.

For example, the following variable declaration in Flash:

greeting = "Hello there " + name + "!";

looks like this in PHP:

$greeting = "Hello there $name!";

Given that name is equal to “Richard”, the greeting variable in both instances would read “Hello thereRichard!”

6. The next section of code actually calls the query:

if (mysql_query ($query)) {

echo "&result=added";

} else {

echo "&result=notadded";

}

?>

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.

Finally, the PHP code is closed using ?>.

7. Save the file as insertScore.php in a new folder called mostwanted within your web sharing or webroot folder, and then close it.

8. Once it’s saved, open it in your browser by typing in the URL.

For the file to be read correctly by the server and PHP parser, the file has to be seen through HTTP pro-tocol. Opening the file regularly from your hard drive just won’t work! If your request was successful,you should see something like this:

22

Page 23: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

The simple reason you’ve opened the file here is to test the temporary variables that you insertedwithin 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 seein 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 thedatabase and user information is correct.

If result is notadded, then chances are your query was written incorrectly. Although queries enable youto 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 incorrectlyand the PHP file couldn’t be parsed because of bad syntax. In this case, check the code strictly, or copythe file insertScore.php, which is available with this chapter’s source code.

9. If you got success in the last step, openphpMyAdmin and select the database and table.Click Browse to view the records.

10. You should see the new added record with Eric’sname and frightfully low score. This proves thatthe PHP file and database are talking to eachother. Keep phpMyAdmin open for now. Nowyou’ll test if Flash interacts with the two.

11. Open the insertScore.php file you saved earlierin your text editor and comment out the follow-ing lines:

//$scoreOutput = 1500;

//$playerOutput = "Eric";

12. Locate the highscore.fla file and move itinto the mostwanted folder you created alittle while ago.

13. Open the highscore.fla file and selectFile ➤ Publish. If your Publish settings arefixed to the default position, this will pub-lish a SWF (highscore.swf) and containerHTML page (highscore.html).

14. Open the highscore.html file from itsHTTP location. Click the Add Score button.

23

Page 24: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

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 andthe text boxes cleared:

In phpMyAdmin, a quick Browse proves that the record has beenadded.

In the eventuality that Eric reappeared, you haven’t resaved thePHP file! In any other unsuccessful eventuality, go back and checkthat the Flash code is correct (or use the source files associatedwith this example).

Otherwise, your high-score table is half done. So far, you can savethe scores, but you’re unable (without phpMyAdmin) to view thescores. All that remains to do to make this fully functional is finishthe Flash file and write a new PHP file. To give you a break fromPHP, you’ll finish the Flash file first.

Creating the Leaderboard Table

The leaderboard table will display the top 10 highest scores and the corresponding player names.

Open the Flash file highscores.fla and inserta blank keyframe on frame 3 of the pages layer.This will house the three columns of theleaderboard.

1. On this layer insert three dynamic text fields,one for the position, player name, and score.

2. Give the text fields the following instancenames (from left to right): positionText,playerText, and scoreText.

3. Give the page a title by changing the AddScore text field to read Show Scores.

24

Page 25: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

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, anonLoad event is set up. In the event of a successful action, you proceed to draw the leaderboard.

5. Add this code:

for (var i = 0; i <= loadData.rows – 1; i++) {

positionText.text += i + 1 + "\n";

playerText.text += loadData["player" + i] + "\n";

scoreText.text += loadData["score" + i] + "\n";

}

The basic premise behind the table drawing is to fill each column with its own relevant data, adding anewline character (\n) after each piece of data. The loop here is set to run according to the value ofloadData.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 asuffixed figure (for example, player2, score5). More on this when you see the PHP file.

6. Now enter the following code:

} else {

statusText.text = "Error loading data.";

}

};

loadData.load("showScores.php?"+Math.round(Math.random()*1000000));

Most of this code should be familiar to you by now, so we’ll save our breath. The last thing to do in thisFlash file is add the code for the Show Scores button.

Note that the random integer query string added to the filename in theload() 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 PHPscript is likely to be unique and fresh. Without this appendage, the browser islikely to cache the page and potentially show the same results as previouscalls to it.

25

Page 26: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

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.

The showScores.php File

1. Open your text editor and type this familiar code:

<?php

$dbhost = "localhost";

$dbusername = "root";

$dbuserpassword = "badger";

$dbname = "mostwanted";

$link = mysql_connect ($dbhost, $dbusername, $dbuserpassword);

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. Thisquery is basically saying this:

“SELECT all fields FROM highscore and ORDER the results according to the score field. Display theresults 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 toextract the data. This $result isn’t to be confused with the result variable that you export later.

3. And now type this:

$count = 0;

while ($query_data = mysql_fetch_array ($result)) {

$player = $query_data ["player"];

$score = $query_data ["score"];

26

Page 27: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

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, thewhile structure is set up. The mysql_fetch_array command is used here to extract a row of data as anarray. The current row or array then is stored in $query_data. The while loop here will run as long asthere are rows to extract from $result.

The next two lines set the variables $player and $score to values extracted from the current rowarray. The values are extracted using what are called associative arrays. As well as the standard numericarray 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 ofthe record directly. For those of you unable to come to terms with this array type, you’ll be glad toknow 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:

$player = $query_data [1];

$score = $query_data [0];

4. Add these few lines:

echo "&player$count=$player";

echo "&score$count=$score";

$count++;

}

Good old echo is used here to send the values from $player and $count out to Flash. As mentionedearlier, 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";

would give the following to Flash:

&score3=2000

Here you increment $count for the next sweep.

5. Finish the code for this file with the following:

echo "&result=okay";

echo "&rows=$count&";

?>

This sends the result variable as normal and also the number of rows reported. The latter is used inFlash 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

Page 28: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

7. Now open the showScores.php file in your browser. The variables are presented in a familiar uglystream:

28

Even though this presentation is ugly, it’s also good because it proves that the query worked. If youcarefully 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 isto check that Flash is playing ball with your PHP file.

8. Run the highscore.html file and click the showscores button. If all went well, you should see abrief ordered list of high scores. If not, check theFlash file code.

All of the files for this tutorial are available in thehighscore folder of this chapter’s source code, whichis downloadable from www.friendsofed.com:

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 ofthe box.

Using the High-Score Table in a Flash GameThe previous exercise is all very well, but it lacks one thing: a game to score from! The point of a high-scoretable of course is to fuel the player into going one better than the other players (or this is at least how I seeit!). With this in mind, I’ve updated Keith Peters’ addictive water game from Chapter 4, enabling it to savescores and reveal the elite firemen corps.

Page 29: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

For this I’ve used my previous FLA code as a base, stitched this onto Keith’s code, and usedshowScores.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 thechanges.

First, because the game only allowed the user to play one game, I had to allow the user to restart. Some ofthe original code then was encapsulated into a function called start. The following code in bold is new oradded:

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 upongame 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

Page 30: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

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();

}

}

The next function is entirely new:

// when game ends this function is called

function onGameOver() {

hs = _root.attachMovie("highscoreTbl", "highscoreTbl",

➥1000005);

hs.gotoAndStop(1);

hs.submitButton.onRelease = function() {

sendData = new LoadVars();

sendData.playerOutput = hs.playerInput.text;

sendData.scoreOutput = score;

hs.statusText.text = "Sending Score to Server...\nPlease wait.";

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();

};

sendData.sendAndLoad("insertScore.php", sendData, "POST");

};

}

Let’s look at what’s happening here. First, a newly added movie clip called highscore page (located in thehigh score assets folder) is attached from the Library. This movie clip contains two frames (as in previousexample): 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 hername as before. This time her score is set as the score variable from the game. This prevents the user fromcheating and entering her own score.

30

Page 31: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

The rest of the code here mimics the previous FLA, with the exception of the getHighScores function callat the end of the onLoad handler. That function is coming right up.

// retrieve high scores

function getHighScores() {

hs.gotoAndStop (2);

loadData = new LoadVars();

hs.statusText.text = "Loading scoreboard.\nPlease wait.";

loadData.onLoad = function() {

if (loadData.result == "okay") {

status_txt.text = "The Top 10 Extinguishers";

hs.statusText.text = "";

//

hs.scoresTxt.text = "";

for (var i = 0; i <= loadData.rows – 1; i++) {

hs.scoresTxt.text += loadData["player" + i] + " ";

hs.scoresTxt.text += loadData["score" + i] + "\n";

}

} else {

hs.statusText.text = "Error loading data.";

}

hs.replayButton.onRelease = function() {

start();

};

};

loadData.sendAndLoad("showScores.php", loadData, "POST");

}

Unlike in the previous FLA, in which you requested the high-score table, this time it’s automatically shownafter 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

Page 32: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

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 justtweaking to make the game run from the start again. The actual saving and retrieving code is only a littledifferent, 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 froma web server URL. The game’s HTML and SWF files should also be in the same folder as the PHP files for itall 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 everyscore 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 beforeadding it. If the score is high enough for, say, the top 100, add it to the database; if it’s lower than the top100, reject it. The best way to do this would be to check the score against the database scores at the endof the game. We’re not going to cover that here, but with a little research it should be within your graspvery soon.

32

Page 33: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

Lollipop BreakIf you’ve made it this far, reward yourself with a lollipop—you’ve done very well. We didn’t say it would beeasy, and it might not have been as fun as some of the earlier chapters, but the important thing is thatyou’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 fromscratch, but to try to get you working with them and also to provide you with a fully functioning high-scoretable. For those of you keen to look into using PHP and MySQL with Flash a little more, we recommend acouple of books from friends of ED: Foundation PHP for Flash and Advanced PHP for Flash will give you asuperb grounding in these technologies. These books, coupled with knowledge of the LoadVars object, willhelp you hit the ground running. And it’s worth staying tuned to www.friendsofed.com to hear about newPHP books.

Dynamic Gaming Case Study: The Race-A-Lot GameTime for a case study. Before you depart, you’lltake a quick look at my Race-A-Lot game. Thissuper lo-fi creation is a simple horse-gamblinggame based on a fairground amusement arcademachine.

Like its arcade equivalent, this game is simple tothe extreme. But it can still draw the punters in!Its key difference is the persistence of playerdata. Each player first registers on the site, isgiven (a virtual) £200, and can gamble. Playerscan then continue their gambling addiction bylogging on at any time using their registered user-name and password.

As you can probably guess, PHP and MySQLare used to do all the magic behind the stor-age of information. Besides the standardupdates, a couple of other options are avail-able that use both technologies:

Personal lifetime gambling statistics

A list of the top gamblers

In this section, we’ll detail some of the hap-penings and show you the PHP code for thedifferent events. Before that, though, let’stalk a little about the actual game.

33

Page 34: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

Race for the PrizeAs previously mentioned, the inspiration for this game is a seaside amusement machine. Not only is thegame a favorite of mine to waste pennies on, but it also has the best sound design (I suppose you can callit that . . .) from a computer/human sample of “Place Your Bets Now, Please!” to the sound of the gatesgoing up and the horses trotting.

First, let me point out that the arcade is a little clunky. It’s a huge triangular glass cabinet with plastic hybridhorse/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 thatrecurs 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 staggeredand nigh-on impossible burst. I did originally try the horses with inertia-based movement, but this was fartoo clean for this particular game.

Another idea stolen from the arcade game is the continual racing of the horses. To attract attention, thehorses continually race, allowing only a brief moment to bet on them. To give a similar live feel to it, I wentwith 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 ofthe 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

Page 35: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

35

In the next few sections, I’ll detail the purpose of every one of the PHP files. This knowledge, coupled withthe FLA, should allow you to make something similar in a snap!

Dissecting the GameA little like the high-scores FLA, the file is split over three keyframes. The first keyframe has a login screen,and the second has a registration screen. The actual game playing takes place on frame 3.

Before you look at the individual files, let’s look at the table structure to see what information is stored foreach player:

Here’s what data the records store:

username: The player’s username data. No two usernames can be the same, so a check is provided toensure that a username isn’t already taken (addUser.php).

password: The individual’s password. This is used for logging on.

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 playeron the My Stats screen.

raceswon: The number of bets the player has won.

racesrun: The number of races the player has bet on.

registerdate: The date the user registered as a player. This data is stored as a UNIX timestamp, a datetaken from the server. I’ve limited this to eight characters, so that it reports the date in the followingformat: yyyymmdd. Timestamps can report the time as well as date.

A typical player’s details then will look like this:

With these details in mind, let’s look at some ofthe dynamic functionality that takes place atdifferent times in the game.

Page 36: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

First Time at the Track, Sir?The registration screen is typical and consists of three textfields: username, password, and a confirmation box for thepassword.

As with any login forms, a number of checks are provided toensure that the user details are correct. Most of these (check-ing the password and confirming password text are identical)are actually processed in Flash. The only check that is donedynamically is to see if the username entered already exists.The submit button actually sends the entered details to theaddUser.php file:

<?php

// addUser.php //

// adds a user's details to the database //

include "connect_db.inc.php";

$query = "SELECT username FROM horses WHERE username = '$userInput'";

$returned = mysql_query ($query);

$rownums = mysql_num_rows ($returned);

if ($rownums > 0) {

echo "&result=userexists";

} else {

$query = "INSERT INTO horses (username, password, winnings,

➥registerdate) VALUES ('$userInput','$passInput', 200, NOW());";

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 enteredin 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 themysql_num_rows command).

The final bold line then checks to see if any rows were returned. In the event that none were returned (theusername doesn’t already exist), the user is added to the database.

36

Page 37: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

The NOW() function here adds the current date to the registerdate field. This fetches the current datefrom the UNIX server as opposed to the user’s own machine.

Down to the NagsLogging in the player is a rather simple affair that calls the loginUser.php file. This time the required checksare processed within the PHP file.

<?php

// loginUser.php //

// login a user //

include "connect_db.inc.php";

$query = "SELECT username, password, winnings FROM horses WHERE

➥username = '$userInput'";

$result = mysql_query ($query);

$rownums = mysql_num_rows ($result);

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, theresult 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 passwordinformation. If the password is correct, the stored cash is sent to Flash; if the password isn’t correct, resultis 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

Page 38: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

Putting the Check in the BankWhen it came to updating the users’ data, I faced a choice. On one hand, I could simply save on logout, orI could save at certain points of the game. The problem with the former choice, of course, is the possibilityof cheating, allowing the player to close the game on bankruptcy. This was simply wrong!

I opted then to save the general data after every five races or, of course, on logout. The thisrace variablein 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 //

$winquery = "UPDATE horses SET winnings = $cash WHERE username =

➥'$userdata';";

$winreturned = mysql_query ($winquery);

// update races run by 1 //

if ($racenum > 0) {

$racequery = "UPDATE horses SET racesrun = racesrun + $racenum

➥WHERE username = '$userdata';";

$runreturned = mysql_query ($racequery);

}

// update won races by 1 //

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 UPDATEcommand is pretty self-explanatory: it simply allows you to update the values stored in a particular field ofa record. Remember that INSERT is used to write a new record. UPDATE therefore is essential for any main-tenance on the records.

An Appointment with the Bank ManagerIn most games, running out of lives or cash usually fills the screen with a dreaded GAME OVER screen, butnot here! Like big old softies, we don’t allow that to happen. When you run out of cash in this game, you’reallowed to continue and you’re handed a wedge of freshly printed notes.

38

Page 39: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

However, the bank manager (who kindly gives you themoney) makes a note of it. The file incrementBankrupt.phpis used to increment it in the database.

<?php

// incrementBankrupt.php //

// add one to bankrupts value /

include "connect_db.inc.php";

$query = "UPDATE horses SET bankrupts =

➥bankrupts + 1 WHERE username =

➥'$userdata';";

$result = mysql_query ($query);

if (!$result) {

echo "&result=error";

}

?>

As with the updateAll.php file, the UPDATE command is called, and the value stored in the bankrupts row isincremented by 1. The value of the bankrupts row is displayed when the user requests her personal statistics.

Racing FormOne of the benefits of storing the user’s data is the ability to recall theuser’s total records at any time. In this game, certain data is kept toallow a user to review her betting abilities. The values stored in theraceswon and racesrun rows, for example, are used to calculate awin/bet ratio.

The bankrupts row is used to shame the player and to calculate theplayer’s total money after bank loans. All of the code here is quitestraightforward:

<?php

// getMyStats.php //

// get user's stats //

include "connect_db.inc.php";

$query = "SELECT * FROM horses WHERE username =

'$userdata';";

$result = mysql_query ($query);

$query_data = mysql_fetch_array ($result);

39

Page 40: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

$player = $query_data ["username"];

$cash = $query_data ["winnings"];

$wins = $query_data ["raceswon"];

$races = $query_data ["racesrun"];

$bankrupts = $query_data ["bankrupts"];

$startDate = $query_data ["registerdate"];

echo "&player=$player";

echo "&cash=$cash";

echo "&wins=$wins";

echo "&races=$races";

echo "&startDate=$startDate";

echo "&bankrupts=$bankrupts";

echo "&result=okay";

?>

Who’s Your Daddy?As with any other game, competition is the key. The high-scoreboard is ordered by the amount of cash in the players’ pockets,but it also displays the players’ win/bet ratio. This allows you tosee if a player just earned all their cash from one race in a totalfluke, or if a player is a consistent earner.

The leaderboard is activated by a button in the bottom-right cor-ner and calls the data from the showLeaderboard.php file:

<?php

// showLeaderboard.php //

// report top 20 players according to score //

include "connect_db.inc.php";

$query = "SELECT * FROM horses ORDER BY winnings DESC LIMIT 0,

➥20;";

$result = mysql_query ($query);

$count = 0;

echo "&result=okay";

while ($query_data = mysql_fetch_array ($result)) {

$player = $query_data ["username"];

$cash = $query_data ["winnings"];

$wins = $query_data ["raceswon"];

$races = $query_data ["racesrun"];

40

Page 41: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

ONLINE GAMING WITH PHP AND MYSQL

if ($wins > 0 && $races > 0) {

$winratio = ($wins / $races) * 100;

$winratio = number_format($winratio, 1);

echo "&player$count=$player";

echo "&cash$count=$cash";

echo "&winratio$count=$winratio";

$count++;

}

}

echo "&rows=$count";

?>

Other PHP FilesThe only other files required by the game are common_db.inc.php (to store MySQL database login infor-mation):

<?php

// common_db.inc.php //

// stores mysql dbase login info //

$dbhost = "<localhost or mysql server>";

$dbusername = "<username>";

$dbuserpassword = "<password>";

$dbname = "mostwanted";

?>

and connect_db.inc.php (to connect to the database):

<?php

// connect_db.inc.php //

// login to database //

include "common_db.inc.php";

$link = mysql_connect ($dbhost, $dbusername, $dbuserpassword);

if (!$link) {

echo "&result=noconnection";

} else {

mysql_select_db($dbname);

}

?>

41

Page 42: %28sample%29 Flash MX 2004 Games Most Wanted - Online Gaming with PHP and MYSQL

FLASH MX 2004 GAMES MOST WANTED

SummaryIt wasn’t possible to go into depth about every aspect of the game here, but I’ve tried to outline some ofthe 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 alittle 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 alsomeant to change according to form and many other variables. I also wanted to make a random horse namegenerator.

If you have any suggestions or comments on the game, I’d love to hear them. E-mail them [email protected], and have fun with these files!

42