public class GameActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//カスタムビュークラスを設定する
MyView view = new MyView(this);
setContentView(view);
}
}
class MyView
extends View {
private int x; //座標のx座標
private int y; //座標のy座標
private int targetW;//ターゲットのサイズ
private int targetH;//ターゲットのサイズ
private int score; //スコア
private Bitmap bmp; //変換後の画像
private Activity activity = (Activity)this.getContext();
Resources res = this.getContext().getResources();//変換後の画像の格納先
{
super(context);
setFocusable(true);
//リソースファイル内の画像をBitmapに変換して格納する
bmp = BitmapFactory.decodeResource(res, R.drawable.tap);
//変換されたBitmapのサイズを取得する。
targetW = bmp.getWidth();
targetH = bmp.getHeight();
//座標の初期化
x = 0;
y = 0;
score = 0;//スコア初期化
}
/********
* 描画
*******/
protected void onDraw
(Canvas canvas
) {
if(score < 200)
{
//背景色を指定
canvas.
drawColor(Color.
WHITE); //白い背景に設定する。 //変換したBitmapで描画
canvas.drawBitmap(bmp, x, y, paint);
//スコアの描画を行う
canvas.drawText("SCORE:"+score+" CLEAR:200", 20.0f, 20.0f, paint);
}
else
{
paint.setTextSize(30.0f);
canvas.drawText("CREAR", 320.0f, 450.0f, paint);
canvas.drawText("Please Tap to Finsh the Game.", 170.0f, 530.0f, paint);
}
}
/********
* タッチ
*******/
public boolean onTouchEvent(MotionEvent event)
{
//画面サイズの取得
int width = getWidth();
int height = getHeight();
//タッチ座標を取得してターゲットとの当たり判定を取る
int touchX = (int)event.getX();
int touchY = (int)event.getY();
if(x < touchX && touchX < x + targetW)
{
if(y < touchY && touchY < y + targetH)
{
//ディスプレイ内に収まるようにランダムな位置を生成する
x
= (int)Math.
round(Math.
random() * width
) - (targetW
/ 2); y
= (int)Math.
round(Math.
random() * height
) - (targetH
/ 2);
//スコア加算
score += 10;
//再描画指令
invalidate();
}
}
//スコアが一定数いったらfinish出来るようになる
if(score > 190)
{
//タッチパネルが敏感なのでちょっと余分にとっておく
if(score > 230)
{
activity.finish();
}
score += 10;
}
return true;
}
}