『enchant.js スマートフォンゲーム開発講座 PRO対応』という本に載っていたゲームを改良して、シンプルなタッチゲームを作った。
iPhone向けにアイコンも作り、manifestファイルを使って一度読み込んだ場合はオフラインでも動作するようにした。
このmanifestファイルで読み込んだデータは、Safariなどのキャッシュを削除するとゲームデータも削除されるようだ。
わたしはこのゲームの中で第一級関数というものを学んだ。
本では、以下のように解説されていた。
第一級関数とは、関数をオブジェクトとてい扱うことができるプログラミング言語の性質。 実行時に関数を生成したり、引数にわたしたり戻り値として返したりダイナミックなプログラミングが可能になる。
このゲームに登場する虫オブジェクトの中で使われている。
/*
* バグクラス
*/
var Bug = Class.create(Sprite, {
// 初期化処理
initialize: function(){
Sprite.call(this, 32, 32);
this.image = game.assets[BUG_IMAGE];
this.rotation = randfloat(0, 360);
this.timer = randfloat(0, BUG_MOVE_TIME);
// 移動処理をセット
this.update = this.move; // this.updateをthis.moveメソッドとして処理する
},
// 移動処理
move: function(){
// 向いている方向に移動
var angle = (this.rotation+270) * Math.PI/180;
this.x += Math.cos(angle) * BUG_SPEED;
this.y += Math.sin(angle) * BUG_SPEED;
// フレームアニメーション
this.frame = 1 - this.frame; // 0<- ->1の切り替えをしている
// 待ちモードに切り替える
if(this.timer > BUG_MOVE_TIME){
this.timer = 0;
this.update = this.wait;
}
},
// 待ち処理
wait: function(){
// 移動モードに切り替える
if(this.timer > BUG_WAIT_TIME){
this.rotation = randfloat(0, 360);
this.timer = 0;
this.update = this.move; // update()という関数が作成されmove()関数として動作させる
// 例) this.update = this.waitとすれば、
// update()関数の動作は、wait()関数として動作する
}
},
// 削除待ち
destroyWait: function(){
this.scaleX = 1.5; this.scaleY = 1.5;
this.opacity = 1 - (this.timer/BUG_WAIT_TIME);
if(this.timer > BUG_WAIT_TIME){
this.parentNode.removeChild(this);
}
},
// ゲームオーバー
gameOverWait: function(){
this.opacity = this.opacity - 0.02;
if(this.opacity <= 0.0){
this.parentNode.removeChild(this);
}
},
// 更新処理
onenterframe: function(){
// ゲームオーバー時
if(game.mode == GAMEOVER){
this.update = this.gameOverWait;
}
// 更新処理実行
this.update();
// タイマー更新
this.timer += 1;
// 画面からはみ出ないよう制御
var left = 0;
var right = SCREEN_WIDTH - this.width;
var top = 0;
var bottom = SCREEN_HEIGHT - this.height;
if(left > this.x) this.x = left;
else if(right < this.x) this.x = right;
if(top > this.y) this.y = top;
else if(bottom < this.y) this.y = bottom;
},
// タッチ開始時処理
ontouchstart: function(){
this.timer = 0;
this.frame = 2;
this.update = this.destroyWait;
this.ontouchstart = null;
game.bugNum -= 1;
},
});
この場合のthis.updateというメソッドは実体を持たない。
その都度、違うメソッドに置き換えられて実行される。
変数と同じで、その都度違う値(振る舞い)をとるようになる。
きわめて、物事をシンプルに捉えて、プログラミングが出来るようになる。
へぇ、こんなものがあったんだ、という感じだった。まあ、わたしの勉強不足に違いないが。
生き物と同じで、プログラミングも進化しているんだなあ、と思う。


コメント