KafunWarsActivity

package org.yasrun.game.kafunwars;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class KafunWarsActivity extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    MyView mView = new MyView(getApplication());

    setContentView(mView);

    mView.start();
  }
}

/**
* 描画用のクラス
*/
class MyView extends View implements Updatable {
  private static final int KAFUN_MAX = 100;

  private Paint myPaint = new Paint();

  private Bitmap bmpHana = null;

  private Bitmap bmpKafun = null;

  private List<Kafun> kafuns = null;

  private UpdateHandler updateHandler = new UpdateHandler(this);

  /**
   * コンストラクタ
   *
   * @param c
   */
  public MyView(Context c) {
    super(c);
    setFocusable(true);
    Resources res = this.getContext().getResources();
    bmpHana = BitmapFactory.decodeResource(res, R.drawable.hana);
    bmpKafun = BitmapFactory.decodeResource(res, R.drawable.kafun);
    kafuns = new ArrayList<Kafun>();
  }

  /**
   * 処理開始
   */
  public void start() {
    update();
  }

  /**
   * タッチイベント
   */
  public boolean onTouchEvent(MotionEvent event) {
    invalidate();
    return true;
  }

  /**
   * メイン
   */
  public void update() {
    if (Math.random() < 0.3 && kafuns.size() < KAFUN_MAX) {
      kafuns.add(new Kafun((int) (Math.random() * 320), 0, (int) (Math.random() * 8) - 4, 8));
    }

    final List<Kafun> deadKafuns = new ArrayList<Kafun>();

    for (Kafun kafun : kafuns) {
      kafun.move();
      kafun.judge();
      if (kafun.isDead()) {
        deadKafuns.add(kafun);
      }
    }

    for (Kafun kafun : deadKafuns) {
      kafuns.remove(kafun);
    }

    invalidate();

    updateHandler.sleep(200);
  }

  /**
   * 描画処理
   */
  protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.BLACK);

    canvas.drawBitmap(bmpHana, 75, 340, myPaint);

    if (kafuns != null) {
      for (Kafun kafun : kafuns) {
        canvas.drawBitmap(bmpKafun, kafun.X, kafun.Y, myPaint);
      }
    }
  }
}
最終更新:2011年03月07日 23:37