Android Open Source - AndroidSDKSample Game View






From Project

Back to project page AndroidSDKSample.

License

The source code is released under:

This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a co...

If you think the Android project AndroidSDKSample listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.van2k.sample.van2kbros;
/*  www.j  a v  a 2  s .c om*/
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.content.res.Resources;
import android.graphics.*;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.van2k.gamesdk.ResultListener;
import com.van2k.gamesdk.Van2k;

public class GameView extends SurfaceView implements SurfaceHolder.Callback {
    private enum STATE {
        TITLE, IN_GAME, GAME_OVER, DISPLAY_RANKING
    }
    private STATE state = STATE.TITLE;

    private MyActivity mActivity;

    private String[] title_button_text = {"Start game", "Ranking"};
    private Rect[] title_button_rect = new Rect[2];

  private float droid_x = 0;  // ???????X??
  private float droid_y = 0;  // ???????Y??
  private int droid_jumping;  // ???????0=??????????????????? 1=1??? 2=2???
  private float droid_vy;    // ???????

  private LinkedList<EnemyInfo> enemy_list =
    new LinkedList<EnemyInfo>();
  private Random random = new Random();

  private float ground_y;    // ???????Y??
  private boolean touch_down;  // ????????????true

  private Timer mTimer = null;
  private float cloud_x;
  private float cloud_y;

  private int score;        // ??

  private Paint paint = new Paint();

  private Bitmap bmpDroid;
  private Bitmap[] bmpEnemy = new Bitmap[3];

    private Handler mHandler;

    // ?????????????????
    private class EnemyInfo {
    public int type;    // ????(0?2)
    public float pos_x;  // X??
    public float pos_y;  // Y??
    public float width;  // ?
    public float height;  // ????
    public float vx;    // ???????
    public float vy;    // ???????

    public EnemyInfo(int enemy_type){
      // ?????????????????
      type = enemy_type;
      width = bmpEnemy[type].getWidth();
      height = bmpEnemy[type].getHeight();
      pos_x = getWidth();  // ???????????????
      pos_y = ground_y - height;

      switch(type){
      case 0 :
        vx = -10;
        vy = 0;
        break;
      case 1 :
        pos_y = ground_y - height;
        vx = -7;
        vy = -20;
        break;
      case 2 :
        pos_y -= 100;
        vx = -5;
        vy = -5;
        break;
      }
    }

    public void onNextFrame(){
      // 30????1?????????????????
      pos_x += vx;
      pos_y += vy;

      switch(type){
      case 1 :
        if (pos_y + height >= ground_y){
          // ????????????????????????
          vy = -20;
        } else {
          vy += 1.5;  // ??????
        }
        break;
      case 2 :
        // ???????????????????????????????
        vy += (ground_y - height - 100 - pos_y) * 0.1;
        break;
      }
    }
  }

  public GameView(MyActivity activity) {
    super(activity);
        mActivity = activity;
        mHandler = new Handler();

    getHolder().addCallback(this);

        // ??????????????????
    Resources r = activity.getResources();
    bmpDroid = BitmapFactory.decodeResource(r, R.drawable.droid);
    bmpEnemy[0] = BitmapFactory.decodeResource(r, R.drawable.enemy1);
    bmpEnemy[1] = BitmapFactory.decodeResource(r, R.drawable.enemy2);
    bmpEnemy[2] = BitmapFactory.decodeResource(r, R.drawable.enemy3);

    // ?????????????????
    // ????????????????????????????????????????????????
    paint.setAntiAlias(true);
  }

    // ???????????????
    private void drawTitleScreen(Canvas canvas){
        // ????????????
        canvas.drawColor(Color.rgb(0, 200, 255));

        // ??????????????
        paint.setColor(Color.rgb(160, 0, 0));  // ??????
        paint.setStyle(Paint.Style.FILL);  // ??????????????????????
        canvas.drawRect(0, ground_y, getWidth(), getHeight(), paint);

        // ????????
        final String text = "Van2k Brothers";
        Rect rect = new Rect();
        paint.setColor(Color.BLUE);
        paint.setTextSize(50);
        paint.getTextBounds(text, 0, text.length(), rect);
        canvas.drawText(text, (getWidth() - rect.width()) / 2, getHeight() / 4, paint);

        // ????????????
        paint.setTextSize(20);
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        if (mActivity.van2k.hasAchievementGiven(1)){
            paint.setColor(Color.RED);
            canvas.drawText("?", 20, 0 - fontMetrics.ascent, paint);
        }
        if (mActivity.van2k.hasAchievementGiven(2)){
            paint.setColor(Color.BLUE);
            canvas.drawText("?", 50, 0 - fontMetrics.ascent, paint);
        }

        // ???
        paint.setTextSize(30);
        fontMetrics = paint.getFontMetrics();
        for(int i = 0; i < title_button_rect.length; i++){
            String button_text = title_button_text[i];
            Rect button_rect = title_button_rect[i];

            paint.setColor(Color.WHITE);
            canvas.drawRect(button_rect, paint);
            paint.setColor(Color.DKGRAY);
            canvas.drawRect(button_rect.left + 2, button_rect.top + 2, button_rect.right - 2, button_rect.bottom - 2, paint);

            paint.setColor(Color.WHITE);
            paint.getTextBounds(button_text, 0, button_text.length(), rect);
            canvas.drawText(button_text, button_rect.left + (button_rect.width() - rect.width()) / 2,
                    button_rect.top + button_rect.height() / 2 - fontMetrics.ascent / 2, paint);
        }
    }

    // ??????????????
  private void drawGameScreen(Canvas canvas) {
    // ????????????
    canvas.drawColor(Color.rgb(0, 200, 255));

    // ??????????????
    paint.setColor(Color.rgb(160, 0, 0));  // ??????
    paint.setStyle(Paint.Style.FILL);  // ??????????????????????
    canvas.drawRect(0, ground_y, getWidth(), getHeight(), paint);

    // ??????????????
    paint.setColor(Color.WHITE);
    canvas.drawOval(new RectF(cloud_x, cloud_y, cloud_x + 100, cloud_y + 30), paint);

    // ??????????
    paint.setColor(Color.BLACK);
    paint.setTextSize(20);
    Paint.FontMetrics fontMetrics = paint.getFontMetrics();
    canvas.drawText("????" + score, 0, 0 - fontMetrics.ascent, paint);

    // ???????????????????
    canvas.drawBitmap(bmpDroid, droid_x, droid_y, paint);

    // ????????
    for(EnemyInfo e : enemy_list){
      canvas.drawBitmap(bmpEnemy[e.type], e.pos_x, e.pos_y, paint);
    }
  }

  @Override
  public synchronized boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();  // X??
    float y = event.getY();  // Y??

    switch(event.getAction()){
    case MotionEvent.ACTION_DOWN :  // ???????????
      // ???????????????????????????????
      if (state == STATE.GAME_OVER){
        state = STATE.TITLE;
                repaint();
        break;
      }
            // ???????????????????????????????????
            if (state == STATE.TITLE){
                for(int i = 0; i < title_button_rect.length; i++){
                    Rect rect = title_button_rect[i];
                    if (rect.contains((int)x, (int)y)){
                        onTitleButton(i);
                        break;
                    }
                }
                break;
            }
      touch_down = true;
      break;
    case MotionEvent.ACTION_MOVE :  // ??????????????????????????
      break;
    case MotionEvent.ACTION_UP :    // ?????????
      break;
    case MotionEvent.ACTION_CANCEL :  // ????????????????????
      break;
    case MotionEvent.ACTION_OUTSIDE :  // ?????????????????????????
      break;
    }
    return true;  // ???????????????????true?????
  }

    // ????????????????????????????????????????
    private void onTitleButton(int button_number){
        switch (button_number){
            case 0 :    // ?????
                startGame();
                break;
            case 1 :    // ?????
                mActivity.van2k.showRanking(MyActivity.VAN2K_RANKING_ID, Van2k.TermType.TOTAL,
                        0, Van2k.CollectionType.TOTAL);
                break;
        }
    }

  private void repaint(){
    // ??????????
    SurfaceHolder holder = getHolder();
    Canvas canvas = holder.lockCanvas();
        if (canvas != null){
            if (state == STATE.TITLE){
                drawTitleScreen(canvas);
            } else {
                drawGameScreen(canvas);
            }
            holder.unlockCanvasAndPost(canvas);
        }
  }

  @Override
  public synchronized void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // ???????Y??
        ground_y = getHeight() / 2;

        // ????????????????????
        final int w = 200;
        final int h = 50;
        final int x = width / 2 - w / 2;
        int y = height / 2 + 10;
        for(int i = 0; i < title_button_rect.length; i++){
            title_button_rect[i] = new Rect(x, y, x + w, y + h);
            y += h * 2;
        }

        repaint();
  }

  @Override
  public void surfaceCreated(SurfaceHolder holder) {
    // ?????????????????????
  }

  @Override
  public synchronized void surfaceDestroyed(SurfaceHolder holder) {
    // ???????????????????????????
    if (mTimer != null){
      mTimer.cancel();  // ??????
      mTimer = null;
    }
  }

  private void startGame(){
        Log.d(MyActivity.TAG, "Start game.");

    // ?????????
    state = STATE.IN_GAME;

    // ?????????
    score = 0;

    // ???????????
    enemy_list.clear();

    // ?????????
    droid_vy = 0;
    droid_jumping = 0;

    // ?????????????
    droid_x = getWidth() / 4;
    droid_y = getHeight() / 2 - bmpDroid.getHeight();

    // ????????????
    touch_down = false;

    // ??????????
    cloud_x = getWidth();
    cloud_y = 50;

    // ?????????????
    repaint();

    // ??????
    mTimer = new Timer();
    mTimer.schedule( new TimerTask(){
      @Override
      public void run() {
        onNextFrame();
      }
    }, 33, 33);  // 33???????????
  }

  private synchronized void onNextFrame(){
        if (state != STATE.IN_GAME) return;

    // ??????
    Iterator<EnemyInfo> itr = enemy_list.iterator();
    while(itr.hasNext()){
      EnemyInfo e = itr.next();
      e.onNextFrame();
      // ?????????????????????????????
      if (e.pos_x < 0) itr.remove();
    }
    // ???????????????????????
    int rand = random.nextInt(50);  // 0?49?????
    if (rand < 3){
      enemy_list.add(new EnemyInfo(rand));
    }

    // ?????????
    if (droid_jumping > 0){
      // ?????
      // 2??????????
      if (touch_down && droid_jumping == 1){
        if (Math.abs(droid_vy) < 2){
          droid_jumping = 2;
          droid_vy = -15;
        }
      }
      droid_vy += 1.5;  // ??????
      droid_y += droid_vy;
      if (droid_y + bmpDroid.getHeight() >= ground_y){
        // ??????????
        droid_y = ground_y - bmpDroid.getHeight();
        droid_jumping = 0;
      }
    } else {
      // ???????????????????
      if (touch_down){
        // ????????????????????????
        droid_jumping = 1;
        droid_y -= 20;
        droid_vy = -20;
      }
     }
    // ???????
    touch_down = false;

    // ??????
    cloud_x -= 3;
    if (cloud_x + 100 < 0){
      cloud_x = getWidth();
    }

    // ????
    score++;

    // ???????
    float droid_cx = droid_x + bmpDroid.getWidth() / 2;
    float droid_cy = droid_y + bmpDroid.getHeight() / 2;
    itr = enemy_list.iterator();
    while(itr.hasNext()){
      EnemyInfo e = itr.next();

      if (Math.abs((e.pos_x + e.width / 2) - droid_cx) < 30
      && Math.abs((e.pos_y + e.height / 2) - droid_cy) < 30){
        // ?????????????????????
        if (droid_y < e.pos_y){
          // ??????????????
          itr.remove();  // ????????????
          score += 100;  // 100???
          droid_vy = -7;  // ???????????
        } else {
          // ??????????
          state = STATE.GAME_OVER;
        }
      }
    }
    if (state == STATE.GAME_OVER){  // ??????????????
      mTimer.cancel();
      mTimer = null;
            sendScore();
    }

    // ??????
    repaint();
  }

    // ??????
    private void sendScore(){
        final int send_score = score;

        // ??????????
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mActivity.van2k.sendScore(MyActivity.VAN2K_RANKING_ID, send_score, new ResultListener() {
                    @Override
                    public void onFinishProcess(ResultListener.Result result) {
                        Log.d(MyActivity.TAG, "sendScore result: " + result.name());
                    }
                });

                // ?????????????
                if (send_score >= 1000) mActivity.van2k.giveAchievement(1, null);
                if (send_score >= 2000) mActivity.van2k.giveAchievement(2, null);
            }
        });
    }
}




Java Source Code List

com.van2k.sample.van2kbros.GameView.java
com.van2k.sample.van2kbros.MyActivity.java