Creating High Score / Top Scores / Data Table in Adobe Flash CS3
15 Oct 2007 Quan Quach 55 comments 11,389 views
Part 3: Using DataGrid Component to create a Table of High Scores
- First, open up Adobe Flash CS3 and start a new file (Actionscript 3.0). Now, be sure to add the DataGrid component or else the program will crash later when you try to run it. To add the DataGrid component, you first have to press CTRL + F7 to bring up the components window as shown below.

- Now, drag the DataGrid icon into your library. You should see the that the component was successfully added into your library, as shown in the figure below. Components must be added to the library before they can be used in the flash applications. If you did not add these components, the flash program will fail to execute.

- Actionscript 3.0 Flash Code. Paste this into the Actions – Frame. If you don’t know how to deal with XML within Flash, it might be a good idea to read up on it. To learn about XML in Flash, click here. In the code shown below, we are making a request to the php script, which queries the MySQL database for the top 15 scores. This information is returned as an XML list and placed into the data table. The code may look archaic, but once you get the hang of dealing with XML within Flash, it should be quite simple.
import fl.controls.dataGridClasses.DataGridColumn; import fl.controls.DataGrid; import fl.data.DataProvider; var myDataGrid:DataGrid = new DataGrid(); var variables:URLVariables = new URLVariables(); variables.playerTime = 5; variables.roundNum = "finalTime"; var request:URLRequest = new URLRequest(); ////insert in the location of the php script ////////// request.url = "insert URL of php script here"; /////////////////////////////////////////////////////// request.data = variables; var loader:URLLoader = new URLLoader(); loader.load(request); loader.addEventListener(Event.COMPLETE, createTable); function createTable(event:Event):void { //typecast the data into XML var myXML:XML = XML(event.target.data); //put the xml data into a DataProvider variable var dp:DataProvider = new DataProvider(myXML); //initialize an empty array var columnArray = []; //initializes the columns of the data table for (var x:Number = 0; x < myXML.children()[0].children().length();x++){ columnArray[x] = new DataGridColumn (String(myXML.children()[0].children()[x].name())); } //sets the width of each column columnArray[0].width = 150; //name columnArray[1].width = 50; //rank columnArray[2].width = 75; //round 1 time columnArray[3].width = 75; //round 2 time columnArray[4].width = 75; //round 3 time columnArray[5].width = 75; //total time //adds the columns to the data grid for (x = 0; x < myXML.children()[0].children().length(); x++) { myDataGrid.addColumn( columnArray[x] ); } //populates the datagrid with the xml data myDataGrid.dataProvider = dp; myDataGrid.width = 500; myDataGrid.rowCount = dp.length; myDataGrid.move(10, 10); myDataGrid.sortableColumns = false; addChild(myDataGrid); }
- The following php code retrieves the top 15 scores, and outputs the result in XML format. Why XML? Using the XML method helps in a number of ways. XML format is very easy to use and makes things much easier in the long run. It helps to keep your data organized and makes it easy to integrate into a Flash environment. If you don’t know much about XML, it might be a good idea to read up on it!
<?php header("Content-type: text/xml"); ////////// FILL IN THIS INFORMATION HERE! //////////// $host = ""; //insert the name of your host here. usually its localhost $user = ""; //insert the name of the user here $pass = ""; //insert the password here $database = ""; //insert name of database wherein table was exported $table = ""; //insert the name of the table //////////////////////////////////////////////////////// $round = $_GET['roundNum']; $linkID = mysql_connect($host,$user,$pass) or die("Could not connect to host."); mysql_select_db($database, $linkID) or die("Could not find database."); $query = "SELECT * FROM {$table} order by {$round} limit 15"; $resultID = mysql_query($query, $linkID) or die("Data not found."); $xml_output = "<flashScores>\n"; for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){ $y = $x +1; $row = mysql_fetch_assoc($resultID); $xml_output .= "\t<entry>\n"; $xml_output .= "\t\t<Name>" . $row['name'] . "</Name>\n"; $xml_output .= "\t\t<Rank>" . $y. "</Rank>\n"; $xml_output .= "\t\t<Round1>" . $row['roundOneTime'] . "</Round1>\n"; $xml_output .= "\t\t<Round2>" . $row['roundTwoTime'] . "</Round2>\n"; $xml_output .= "\t\t<Round3>" . $row['roundThreeTime'] . "</Round3>\n"; $xml_output .= "\t\t<Total>" . $row['finalTime'] . "</Total>\n"; $xml_output .= "\t</entry>\n"; } $xml_output .= "</flashScores>"; echo $xml_output; ?>
- Now, go back to your Flash file, and execute the program. If you did everything correctly, you should see the data table! I recommend you take some time to go over the code because this is probably the most difficult part of this tutorial.


I was not able to extract the zip file for this tutorial. It would be nice to have the original files. Thanks for all the hard work.
Sorry, we’re having some server issues. We are trying to resolve them ASAP.
man, i could rly use the source file…
i cant find out why Flash CS3 compiler gives me these errors:
1172: Definition fl.controls:TextInput could not be found.
1172: Definition fl.controls:TextArea could not be found.
aha! ive done it! thank you very very very much
btw quite funny that youve answered the guy sooner than he asked…
J
how did you figure it out?
i’ll have the source file uploaded and working at 1030pm pst. check back then!
You are God! OK, maybe just a minor deity.
to solve these errors:
1172: Definition fl.controls:TextInput could not be found.
1172: Definition fl.controls:TextArea could not be found.
simply add this at the top of your code:
import fl.controls.TextInput;
import fl.controls.TextArea;
wheen i say top of your code, i mean in frame 1 (if theres no class .as file) or if there is a class file that the code is done in, you would put it here:
package
{
import fl.controls.TextInput;
import fl.controls.TextArea;
public class ClassName …….
{
}
}
The source code can be downloaded but the fla file cannot be extracted… CRC error
What about if you put the imports in but it still throws that error?
just delete the import..not sure of the consequences,but it can run
Please write more tutes like this one your excellent !!
Excellent tutorial, thanks!
Can you briefly explain how would you pull an image from mysql and display it in flash? Thanks! -igor
Help. The program did work (go to http://newmedia.purchase.edu/~Jeanine/videoproject/choosevideoplay.html
but when I went in to make a slight change in the positioning of the FLVPlayback, Publish produces errors, namely 1172 Definition fl.video:FLVPlayback could not be found.
It was found before????
Now there was an Adobe update. Could that be the problem?
thanks in advance.
FOUND IT!
This was pretty subtle. The fl.video classes are only accessible if there is a FLVPlayback in the Library. Now, when I did this the first time, I had another .fla file open with a FLVPlayback component in its Library, so the Publish worked.
You and your tutorials have helped me before and I’m sure you will help me again.
Hi!
How can I chage highscore output that it puts scores in a different order.
The biggest score first and so on. I use it in a game where player needs to get as much points as he can. Thanks
You have to change the way you query the MySQL database in order to change the order. Maybe you can also change the order within flash. I haven’t coded in actionscript in a while, so I’m very rusty!
“You have to change the way you query the MySQL database” What I should do with the
database? Which parameters need to change? Im not a MySQL guru
I would suggest reading up on mysql basics.
Here’s a good place to start: http://www.webdevelopersnotes.com/tutorials/sql/mysql_tutorial_selecting_data_using_conditions.php3
Thanks! Now it works as it should be!
jgvasdkjcfjashvbcuyafcvsdcscas
no comments
no
hi i didnt see
Very nice
I am still struggling with this error
1172: Definition fl.controls:TextInput could not be found.
1172: Definition fl.controls:TextArea could not be found.
The lines
import fl.controls.TextInput;
import fl.controls.TextArea;
are in frame 1 and are at the top of the code. What the heck am I doing wrong. I am a newbie at ActionScript, I think I am missing something very basic that I just don’t have the background yet to understand.
Hi
To add an fl control it must be in ur library.
Thanks very much! Very very useful and good starting point to learn XML and PHP better. It helps when you’ve managed to make something very useful actually work, before learning more of the code. A base point to start from, where I can see the start to the finish…so thanks very much!
I had to delete the first 2 lines of the Actionscript files sometimes to make them work.
XYZ said: “to add an fl control it must be in ur library”.
Sorry but, how can I put it in the library?
Thanks
you should see all the controls in the Component window. If it’s not on the right side of the CS3 application, go to the menu above and select “Window” and then find “Component”.
The error with the lines
import fl.controls.TextInput;
import fl.controls.TextArea;
Can be resolved by putting a Dynamic text field on the stage with an instance name of ‘writingCompleted’ and changing the completeWriting function to this:
function completeWriting(event:Event):void {
writingCompleted.text = event.target.data;
}
I got this same error, and this was a workaround. Great tutorial though!
Доброго времени суток, форумчане сайта http://www.blinkdagger.com
Ответьте мне, пожалуйста, на несколько вопросов…
- какая программа умеет автоматически за НЕСКОЛЬКО СЕКУНД регистрировать ящики на mail.ru и многих других почтовиках?
- какая программа умеет автоматом рассылать по mamba.ru и loveplanet.ru по заданным параметрам, при этом еще поддерживая функции автоответчика?
- а также сможет разослать по форумам текст (например) “где купить валенки?”, а потом в ответ на этот текст ОТ ДРУГОГО имени и IP написать (например) “только на сайте megavalenki.ru!”?
- плюс распознаёт картинки и вопросы а-ля “что написано на этой картинке?”, “сколько будет 2+2?” и “какой сейчас год?” и умеет корректно на них отвечать?
- какая программа сможет разослать топики по форумам, попутно автоматически регистрироваться на них и создавая подробный отчет о проделанной работе?
- и при этом работает с разнообразными движками - phpBB, VBulletin, IPB, ExBB, Icon Board, YaBB, UltimateBB, множеством различных гостевых, досок и блогов?
- какую программу вы МОЖЕТЕ переделать под свой вкус?
- какая программа автоматически обновляет прокси / SOCKS, обеспечивая вам полную анонимность? (достаточно просто нажать ОДНУ кнопку)
- какая программа умеет рассылать персональные сообщения всем пользователям форумов phpBB, IPB, VBulletin?
- какая программа отсортирует Вашу базу ссылок по Google PageRank?
- какая программа МАССОВО отредактирует все Ваши ранее разосланные объявления по форумам?
- и при этом еще регулярно обновляется и совершенствуется.
Ответ ОДИН: всё это и многое другое под силу программному комплексу XRumer 4.085 Platinum Edition + Hrefer 2.85
Данный комплекс имеет множество отзывов на авторитетных источниках (Washington Post, Wikipedia и т.п.), имеет историю активного развития более 3-х лет.
Просто спроси у Яндекса!
См. также: массовые рассылки, распознавание текстовой защиты, мощная спамилка, PPC, дорвеи, софт для SEO, рассылка по форумам, программы для SEO, white SEO, XRumer Platinum, постинг, XRumer 2.9 устарел, хрумер 2.9 устарел, ППЦ, распознавание графической защиты, XRumer, рефспам, линкспам, хрумер 3.0 устарел, doorways, SEO, постинг по блогам, разослать по форумам и гостевым, софт для СЕО, белое СЕО, чёрное СЕО, программы для СЕО, black SEO, распознавание капчи, хрумер, суперсофт для SEO, СЕО
I get this error when trying to import sampleFlashDatabase.sql:
Error
SQL query:
– phpMyAdmin SQL Dump
– version 2.10.0.2
– http://www.phpmyadmin.net
–
– Host: localhost
– Generation Time: Sep 27, 2007 at 11:34 PM
– Server version: 5.0.37
– PHP Version: 4.4.4
SET SQL_MODE = “NO_AUTO_VALUE_ON_ZERO”;
MySQL said:
#1064 - You have an error in your SQL syntax near ‘SQL_MODE=”NO_AUTO_VALUE_ON_ZERO”‘ at line 2
I got it, it’s working great! I’m so happy!
Скажите, а у вас есть RSS поток в этом блоге?
Приветствую. А не подскажете, где можно найти такую же информацию, но только чтобы она была на английском языке
Good 235rter2rwer23r
Hi,
I’ve used your tutorial for the highscore system, is working fine but the only problem is that everytime i submit a new score I have to restart the Flash ide cause the new score is not displayed.
I mean the new scores are normally written to the db but parsing the xml file I’m always getting the first score table, the one not updated.
Any suggestions?
Thanks
This tutorial was great.
it was only a cache problem related to the xml…
now it works
I have a game already developed. What process would I use to use this within my already developed game? Thank you.
Bah… I went through all this just to realize that if I change my Actionscript to 3.0, Actions cannot be run from movie clips or instances. I think a lot of my game depends on that.
This just begs one question: how would you prevent hacked scores from entering the database? For example, if I were to open a browser and navigate to that URL with much-too-high scores, the database would insert a bogus record.
Also, make sure that you escape input before inserting a database record. (mysql_real_escape_string) Otherwise, your database could be compromised.
Хороший пост! Подчерпнул для себя много нового и интересного!
Пойду ссылку другу дам в аське
Автор, посты у вас, конечно, интересные. Но вы не думали поменять дизайн?
Так ведь без недостатков достоинства не так заметны
Все замечательно: и по стилю изложения, и по содержимому. Так держать!
Хм…, а я тут за свои годы, как-то привык ко всему этому, даже внимания на это не обращаю
Вы тоже привыкнете
Lol “Sorry, we’re having some server issues. We are trying to resolve them ASAP.” Lol ! 1 and a half year later… no answer!! LMAO!
Ой, благодарю
Давно искала эту информацию, спасибо.
Огромное человеческое спасибочки !
Огромное вам человеческое спасибо, очень актуальная заметка.
Что-то футер у вас вправо съехал (в опере при разрешении 1024х768)
[...] was creating my high scores based on this great tutorial I read some way back, but I wasn’t very satisfied with the overall performance of that [...]
[...] I visited. As usually, google was a big help. I found this great article from speckyboy magazine, 12 WP Plugins to Display and Highlight Code within your Blog, wich was all I needed to start. The problem now was chosing and testing the options [...]