nayzuko.com || animation n web tutorial

Highscore Flash, PHP dan Mysql

Email Print PDF

Highscore FlashTutorial ini hanya untuk menunjukkan koneksi flash dengan database. Jadi abaikan game-nya! Ada dua swf, pertama game; dan kedua highscore table. Keduanya dihubungkan dengan LocalConnection.

Script dan file game ini karya emanueleferonato.com dan flash-creations.com.

PREVIEW

Pertama, buat tabel di Database Anda dengan phpmyadmin.
Dumb sql berikut ini yang akan membuat tabel "datague".

--
-- Table structure for table `datague`
--

CREATE TABLE IF NOT EXISTS `datague` (
  `id` mediumint(9) NOT NULL AUTO_INCREMENT,
  `nickname` varchar(50) NOT NULL DEFAULT '',
  `dateposted` varchar(10) NOT NULL DEFAULT '',
  `score` mediumint(9) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;

--
-- Dumping data for table `datague`
--

INSERT INTO `datague` (`id`, `nickname`, `dateposted`, `score`) VALUES
(3, 'myname', '2005-09-10', 150),
(4, 'sape nih', '2005-03-05', 330),
(5, 'whatsususd', '2011-02-16', 100),
(8, 'fdfg', '2011-03-14', 1000),
(9, 'zzztes', '2011-03-14', 3),
(10, 'testtambahan', '2011-03-14', 4),
(11, 'lagiah', '2011-03-14', 12),
(12, 'testagain', '2011-03-14', 3),
(13, 'mygame', '2011-03-14', 1095),
(14, 'submit', '2011-03-14', 800),
(15, 'again', '2011-03-14', 1755),
(16, 'testmes', '2011-03-14', 1085),
(17, 'testing local', '2011-03-14', 217),
(18, 'tambahan', '2011-03-14', 120);

Berikut ini file untuk mengambil score. Save as "getscores.php" atau terserah (asal diingat).

<?
/*
   Retrieves score data from highscores table and returns 
                  data and status to Flash
   
   errorcode:
      0: successful select
      1: can't connect to server
      2: can't connect to database
      3: can't run query
*/

//  fill this in with the right data for your server/database config
$server = "localhost";
$username = "root";
$password = "";
$database = "flashmysql";

//  mysql_connect: Open a connection to a MySQL Server
//  Returns a MySQL link identifier on success, or FALSE on failure.
if (!mysql_connect($server, $username, $password)) {
   $r_string = '&errorcode=1&';	
	
//  mysql_select_db: Sets the current active database on the server that's associated 
//    with the specified link identifier. Every subsequent call to mysql_query() 
//    will be made on the active database.
//  Returns TRUE on success or FALSE on failure.
} elseif (!mysql_select_db($database)) {
   $r_string = '&errorcode=2&';
	
//  mysql_query: Sends a query (to the currently active database
//  For SELECT, SHOW, DESCRIBE or EXPLAIN statements, mysql_query() returns a 
//     resource on success, or FALSE on error.  
//  For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_query() 
//     returns TRUE on success or FALSE on error. 
} else {
   $qr = mysql_query("SELECT * from datague");
   if (!qr || mysql_num_rows($qr)==0) {
      $r_string = '&errorcode=3&msg='.mysql_error().'&';
   } else {
      $r_string = '&errorcode=0&n='.mysql_num_rows ($qr);
      $i = 0;
      while ($row = mysql_fetch_assoc ($qr)) {
         while (list ($key, $val) = each ($row)) {
            $r_string .= '&' . $key . $i . '=' . stripslashes($val);
         }
         $i++;
      }
      // add extra & to prevent returning extra chars at the end
      $r_string .='&';
   }
}
echo $r_string;
?>



Berikut ini file untuk mengupdate skor. Save as "insert.php" atau terserah.
<?
/*
  inserts record into highscores table, returns new 
                     record id and status to Flash
*/

// fill with correct data for your server configuration
$server = "localhost";
$username = "root";
$password = "";
$database = "flashmysql";

if (!mysql_connect($server, $username, $password)) {
   $r_string = '&errorcode=1&';	
	
} elseif (!mysql_select_db($database)) {
   $r_string = '&errorcode=2&';
	
} else {
   $ins_str = "INSERT INTO datague VALUES (NULL, '".addslashes($_GET['nickname'])."', '".$_GET['dateposted']."', '".$_GET['score']."')";

   if (!mysql_query ($ins_str)) {
      $msg = mysql_error();
      $r_string = '&errorcode=3&msg='.$msg;
   } else {
      // pass back id of inserted record
      $id = mysql_insert_id();
      $r_string = '&errorcode=0&id='.$id.'&';
   }
}

echo $r_string;
?>



Selanjutnya kita akan menambahkan actionscript. Buka Flash 8 (CS3 juga gak apa-apa karena ini AS2).
f8.png
Download semua file tutorial.




Esktrak semua filenya di folder htdocs atau www, atau folder lain dalam server lokal.

Ada dua file flash: congame.fla dan sistemskor.fla
Dua file php: "getitem.php" dan "insertitem.php"
File sql utk dump: "datague.sql"
Dan file html: "congame.html" yang berisi dua swf (congame.swf dan sistemskor.swf)

Dua file swf tersebut dikonek dengan LocalConnection.
Sehingga skor game di congame akan dimasukkan dalam sistem skor.

Dalam sistem skor ada actionscript yang akan mengambil skor yang dibuat di congame.swf


Pada "getitem.php" dan "insertitem.php", ganti variabel database dengan nama database Anda. Di sini db-nya "flashmysql"
$server = "localhost";
$username = "root";
$password = "";
$database = "flashmysql";

Pada file "sistemskor.fla"

Ada skrip dg path absolute (jika sudah online):

if (_url.indexOf("http") != 0) filepath = "http://web_Anda.com/folder/";
else filepath = "../folder/";


Ganti dengan path lokal untuk tes di lokal.

if (_url.indexOf("http") != 0) filepath = "http://localhost/folderfileAnda/";
else filepath = "../folderfileAnda/";


Selebihnya sudah jelas ada keterangan dalam file fla.


KOMPILASI HIGHSCORE DALAM SATU SWF
Jika tidak ingin menggunakan dua swf, berikut ini cara menjadikannya satu swf tanpa memakai LocalConnection dan SharedObject.

PREVIEW


Buka "sistemskor.fla" dan copy actionscript di layer "actions".
Buka "congame.fla" dan paste script tadi di bawah script yang sudah ada.

Berikutnya, copy semua symbol utk skor di dalam "sistemskor.fla" kecuali dynamic text "currentscore". paste semuanya di dalam "congame.fla"

Isi actionscript di "congame.fla":
//var send_score:LocalConnection = new LocalConnection(); //kita buang LocalConnection
_root.attachMovie("score", "score", 1);
_root.attachMovie("hero", "hero", 2, {_x:250, _y:200});
_root.attachMovie("target", "target", 3, {_x:Math.random()*400+25, _y:Math.random()*300+25});

scores_dg._visible=0; //TAMBAHAN 1
showallscore._visible=0; //TAMBAHAN 2
enemy_power = 3;
points = 0;
//score_ti.text=points;
max_score = 0;
hero.onEnterFrame = function() {
 this._x = _root._xmouse;
 this._y = _root._ymouse;
};
target.dir = Math.random()*2*Math.PI;
target.xspeed = enemy_power*Math.cos(foe.dir);
target.yspeed = enemy_power*Math.sin(foe.dir);
target.onEnterFrame = function() {
 dist_x = this._x-hero._x;
 dist_y = this._y-hero._y;
 distance = Math.sqrt(dist_x*dist_x+dist_y*dist_y);
 if (distance<(hero._width+this._width)/2) {
 points+=20;
 //if (points>max_score) { // kita buang LocalConnection dan konek data SharedObject
 //    max_score = points;
 //    send_score.send("hall_of_fame", "compare_scores", points);
 //}
 score_ti.text = points;
 this._x = Math.random()*400+25;
 this._y = Math.random()*300+25;
 foe = _root.attachMovie("enemy", "enemy", _root.getNextHighestDepth(), {_x:Math.random()*400+25, _y:Math.random()*300+25});
 foe.dir = Math.random()*2*Math.PI;
 foe.xspeed = enemy_power*Math.cos(foe.dir);
 foe.yspeed = enemy_power*Math.sin(foe.dir);
 foe.onEnterFrame = function() {
 this._x += this.xspeed;
 this._y += this.yspeed;
 if ((this._x<0) or (this._x>500)) {
 this.xspeed *= -1;
 }
 if ((this._y<0) or (this._y>400)) {
 this.yspeed *= -1;
 }
 dist_x = this._x-hero._x;
 dist_y = this._y-hero._y;
 distance = Math.sqrt(dist_x*dist_x+dist_y*dist_y);
 if (distance<(hero._width+this._width)/2) {
 points--;
 score.scoretxt.text = points;
 this.removeMovieClip();
 }
 };
 }
};
///tambahan

// for select query
var select_lv:LoadVars = new LoadVars();
// for insert query
var insert_lv:LoadVars = new LoadVars();
// for delete query
var delete_lv:LoadVars = new LoadVars();
// get today's date
var today:Date = new Date();
// index of item to be deleted
var deleteIndex:Number;

var errorMsgs:Array = [
 "",        
 "Tidak bisa konek ke server. Cek server Anda.",
 "Tidak bisa konek ke database. Cek konfigurasi database Anda",
 "Query Anda salah",
 "Dua entry awal tidak bisa dihapus. cek deleteitem.php"];

// create a string to show where to access the PHP script
var filepath:String;

// create an array to be the dataprovider for the datagrid
var scoreInfo:Array = [];

// create an object to listen for clicks on datagrid headers to do correct sort
var headerListener:Object = {};
headerListener.headerRelease = function(event:Object) {
 switch (event.columnIndex) {
 case 0:
 if (scores_dg.getColumnAt(0).sortedUp) {
 scores_dg.sortItemsBy(scores_dg.columnNames[0], Array.CASEINSENSITIVE | Array.DESCENDING);
 } else {
 scores_dg.sortItemsBy(scores_dg.columnNames[0], Array.CASEINSENSITIVE);
 }
 scores_dg.getColumnAt(0).sortedUp = !scores_dg.getColumnAt(0).sortedUp;
 break;
 case 1:
 if (scores_dg.getColumnAt(1).sortedUp) {
 scores_dg.sortItemsBy(scores_dg.columnNames[1], Array.NUMERIC | Array.DESCENDING);
 } else {
 scores_dg.sortItemsBy(scores_dg.columnNames[1], Array.NUMERIC);
 }
 scores_dg.getColumnAt(1).sortedUp = !scores_dg.getColumnAt(1).sortedUp;
 break;
 }
}

// function to put a zero in front of a one-digit number
function zerofill(n:Number):String {
 if (n<10) return '0' + n.toString();
 else return n.toString();
}

// set the path to the PHP script based on whether this is being tested
// locally or online.  If local, use script saved on online webserver.
// Can use http://localhost instead if script is on local webserver.

if (_url.indexOf("http") != 0) filepath = "http://localhost/folder/";//ganti dg folder Anda
else filepath = "../folder/";

// limit fields to max characters allowed by database
nickname_ti.maxChars = 50;
date_ti.maxChars = 10;

// put in some default values
score_ti.text = points;
date_ti.text = today.getFullYear() + '-' + zerofill(today.getMonth()+1) + '-' + zerofill(today.getDate());

select_lv.onLoad = function(ok:Boolean) {
 if (ok) {
 if (this.errorcode=="0") {
 for (var i:Number=0; i < this.n; i++) {
 scoreInfo.push(
 {record:this["id"+i],
 nickname:this["nickname"+i],
 score:Number(this["score"+i]),
 dateposted:this["dateposted"+i]
 });
 }
 // only display Nickname, Score, and Date Posted (not record id)
 scores_dg.columnNames = ["nickname", "score", "dateposted"];
 // set formatting of nickname column
 scores_dg.getColumnAt(0).width = 200;
 // trap header click event to sort case-insensitive on this field
 scores_dg.getColumnAt(0).sortOnHeaderRelease = false;
 // this property will keep track of whether sort is ascending or descending
 scores_dg.getColumnAt(0).sortedUp = false;
 scores_dg.getColumnAt(0).headerText = "Nama";
 // set formatting of score column
 scores_dg.getColumnAt(1).width = 100;
 // trap header click event to sort numerically
 scores_dg.getColumnAt(1).sortOnHeaderRelease = false;
 scores_dg.getColumnAt(1).sortedUp = false;
 scores_dg.getColumnAt(1).headerText = "Jumlah";
 // set formatting of date column
 // auto-sort will work fine for this column
 scores_dg.getColumnAt(2).width = 160;
 scores_dg.getColumnAt(2).headerText = "Tanggal Masuk Item";
 
 // set dataProvider for datagrid
 scores_dg.dataProvider = scoreInfo;
 // execute headerRelease function for correct sort when user clicks a header
 scores_dg.addEventListener("headerRelease", headerListener);
 msg_ta.text = "Masukkan data dan klik Add untuk menambah data.  Klik barisnya untuk menghapus, dua baris paling atas tidak bisa dihapus.";
 } else {
 // show kind of error
 msg_ta.text = errorMsgs[Number(this.errorcode)];
 // if query error, show mysql_error
 if (this.errorcode == "3") msg_ta.text += ": " + this.msg;
 }
 } else {
 // if loadvars failed (eg, if script not found)
 msg_ta.text = "Loadvars gagal";
 }
}
msg_ta.text = "Mengambil data dari database...";
select_lv.sendAndLoad(filepath + "getitem.php", select_lv, "GET");

// function to execute after insertscore.php has run
// it returns errorcode, msg (sql error), id (of most recent insert)
insert_lv.onLoad = function(ok:Boolean) {
 if (ok) {
 if (this.errorcode == "0") {
 // update the dataProvider so datagrid updates
 scoreInfo.addItem(
 {record:this.id,
 nickname:nickname_ti.text,
 score:Number(score_ti.text),
 dateposted:date_ti.text
 });
 // reset fields
 nickname_ti.text = '';
 score_ti.text = '';//TAMBAHAN 3
 points = 0;//TAMBAHAN 4
 showallscore._visible=1; //TAMBAHAN 5
 date_ti.text = today.getFullYear() + '-' + 
 zerofill(today.getMonth()+1) + '-' + 
 zerofill(today.getDate());
 msg_ta.text = "Data telah ditambahkan ke database";
 } else {
 // show kind of error
 msg_ta.text = errorMsgs[Number(this.errorcode)];
 // if query error, show mysql_error
 if (this.errorcode == "3") msg_ta.text += ": " + this.msg;
 }
 } else {
 // if loadvars failed (eg, if script not found)
 msg_ta.text = "Penambahan data gagal";
 }
};

function insertRecord() {
 // check for no name or bad score
 if (nickname_ti.text == '') {
 msg_ta.text = "Masukkan nama";
 } else if (isNaN(score_ti.text) || 
 Number(score_ti.text) < 0 || 
 Number(score_ti.text) > 65000) {
 msg_ta.text = "Jumlah harus di antara 0 and 65000";
 } else {
 insert_lv.nickname = nickname_ti.text;
 insert_lv.score = score_ti.text;
 insert_lv.dateposted = date_ti.text;
 insert_lv.sendAndLoad(filepath + "insertitem.php", insert_lv, "GET")
 }
}

function showRecord() { //TAMBAHAN 6
scores_dg._visible=1;    
}
add_btn.addEventListener("click", insertRecord);

showallscore.addEventListener("click", showRecord);//TAMBAHAN 7  


Tambahan dalam script berfungsi untuk membuat skor kembali ke 0 ketika selesai submit
dan tombol "showallscore" muncul. Ketika tombol ini diklik, movie highscore muncul.

Copy button "add_btn" dan namakan "showallscore".

TAMBAHAN 1 >> buat invisible table highscore ("scores_dg"). Jadi ketika bermain, tabel ini tidak kelihatan
TAMBAHAN 2 >> buat invisible tombol "show all score"
TAMBAHAN 3 & 4 >> clear score teks dan score point setelah submit score
TAMBAHAN 5 >> buat visible tombol "show all score"
TAMBAHAN 6 >> buat fungsi untuk memperlihatkan tabel highscore
TAMBAHAN 7 >> tombol showallscore akan memunculkan tabel highscore ketika diklik

Untuk mengurutkan score dan menampilkan 10 skor terbaik misalnya:
Buka "getitem.php" pada baris ke-37 tambahkan ordernya:
 $qr = mysql_query("SELECT * from datague order by score desc LIMIT 0 , 10");
 


Catatan akhir:
Bagi yg belum tahu, sistem skor ini hanya bisa dilihat di browser dengan server lokal (XAMPP, WAMPP dst) Apache dan MySQL aktif.
Jika ingin melihat hasil perubahan terbaru pada flash ketika di browser, selalu clear cache (Clear Recent History pada FF) karena  browser biasanya cache .swf.

Download fla kompilasi satu file. (jangan lupa donwload file php yang telah disebutkan sebelumnya)
f8.png