實例17–無敵搶錢雞 – Android移動開發技術文章_手機開發 Android移動開發教學課程

  隨著轉化的進行,難度也在增加,這次的實例我弄瞭一天,當然有些時間是在弄其他的,隨著代碼量的增加,要更加理解源代碼的結構,我這次采用uml弄出他們的各個類圖和結構,這樣讓我更瞭解原作者的思想…然後再用android的方法的實現,當然因為都是java開發的,有些類是直接用的,這次還是使用瞭我本來的寫的android_midp包,在androidSprite類中添加瞭碰撞方法.
下面是效果圖:


 

 

 

MainView.java
Java代碼 
package com.wjh.demon_17; 
 
import java.util.Random; 
 
import com.wjh.midp_me.GameView; 
 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.util.Log; 
import android.view.MotionEvent; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 
import android.view.SurfaceHolder.Callback; 
 
public class MainView extends SurfaceView implements Callback,Runnable{ 
     
     
    public static final int GAME_UI     = 0;    //進入用戶界面 
    public static final int GAME_GAMING = 1;    //進行遊戲 
    public static final int GAME_END        = 2;    //遊戲結束 
    public static final int GAME_STATE_NUM = 3; //狀態總數 
    private int m_nState    = GAME_UI;              //存儲當前的遊戲狀態 
     
    private boolean     m_bRunning;             //控制線程運行 
    private MyBack          m_Back;                 //遊戲背景 
    private MyUI            m_UI;                   //用戶界面   
    private ChickSprite m_Chick;                //管理小雞對象 
    private GoodsSprite m_Goods[];              //管理物品對象 
    private int         m_nScore = 0;           //當前得分 
    private int         m_nTime = 60 * 10;      //遊戲總時間 
    private Random          m_Random; 
    private int screenStartX = 0;//遊戲界面開始坐標X 
    private int screenStartY = 0;//遊戲界面開始坐標Y 
    private int screenWidth = 0;//遊戲界面寬度 
    private int screenHeight =0;//遊戲界面高度 
     
    private Context context ; 
    int keyState = 0; 
    Thread gameThread = null; 
    SurfaceHolder holder = null; 
    public MainView(Context context) { 
        super(context); 
        // TODO Auto-generated constructor stub 
         
        this.context = context; 
        setFocusable(true); 
        setFocusableInTouchMode(true); 
        holder = this.getHolder(); 
        holder.addCallback(this);    
    } 
    private void initView() 
    { 
        m_Random = new Random(); 
        m_Back = new MyBack(context); 
        m_UI = new MyUI(context); 
        screenStartX = (getWidth() – m_Back.getBackImageWidth())/2; 
        screenStartY = (getHeight()-m_Back.getBackImageHeight())/2; 
        screenWidth = screenStartX+m_Back.getBackImageWidth(); 
        screenHeight = screenStartY+m_Back.getBackImageHeight(); 
         
        try{ 
            //讀取小雞精靈圖片,並設置小雞的初始位置 
            Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.chick); 
            m_Chick = new ChickSprite( img, 31, 29); 
            m_Chick.setRefPixelPosition( getWidth() / 2, screenHeight- 18 ); 
             
            //讀取物品圖片,屏幕上最多同時掉落6個物品 
            img = BitmapFactory.decodeResource(getResources(), R.drawable.goods); 
            m_Goods = new GoodsSprite[6]; 
            for( int n = 0; n < m_Goods.length; n ++ ) 
                m_Goods[n] = new GoodsSprite( img, 19, 19 ); 
        } 
        catch (Exception ex){}  
        setState(GAME_UI);                          //設置遊戲狀態 
    } 
    private void setState( int state ){         //設置當前的遊戲狀態 
        if( state < 0 || state >= GAME_STATE_NUM ) 
            return; 
        m_nState = state; 
    } 
    @Override 
    public void run() { 
        // TODO Auto-generated method stub 
        while(m_bRunning) 
        { 
            input(); 
            logic(); 
            doDraw(); 
            try { 
                Thread.sleep(100); 
            } catch (InterruptedException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } 
        } 
         
    } 
    //開始遊戲主線程 
    public void start() 
    { 
        if(gameThread == null) 
        { 
        gameThread = new Thread(this); 
        gameThread.start(); 
        m_bRunning = true; 
        } 
    } 
    //停止遊戲主線程 
    public void stop() 
    { 
        m_bRunning = false; 
        if(gameThread != null) 
        { 
            try { 
                gameThread.join(); 
            } catch (InterruptedException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } 
        } 
    } 
    private int getKeyStates() 
    { 
        return keyState; 
    } 
    private void setKeyStates(int keyStates) 
    { 
        this.keyState = keyStates; 
    } 
    //輸入判斷 
    public void input() 
    { 
        //根據不同的遊戲狀態,處理按鍵操作 
                int keyStates = getKeyStates(); 
                switch( m_nState ){ 
                case GAME_UI:                               //進入用戶界面 
                    m_UI.Input(keyStates); 
                    if( m_UI.getState() == MyUI.UI_HIDE )   //當用戶界面被隱藏時進入遊戲 
                        setState(GAME_GAMING); 
                    break; 
                case GAME_GAMING:                           //進入遊戲 
                    if( m_nTime <= 0 )                       //如果遊戲超時 
                        return;  
                    m_Chick.Input(keyStates,screenStartX,screenStartY,screenWidth,screenStartY); 
                    break; 
                } 
    } 
    //邏輯判斷 
    public void logic() 
    { 
        //根據不同的遊戲狀態,處理邏輯操作 
                switch( m_nState ){ 
                case GAME_UI:                               //進入用戶界面 
                    break; 
                case GAME_GAMING:                           //進入遊戲 
                    m_Chick.Logic(); 
                    for( int n = 0; n < m_Goods.length; n ++ ) 
                    m_Goods[n].Logic(screenHeight-10); 
                    Collides();                             //碰撞檢測 
                    CreateGoods();                          //隨機生成新物品 
                    m_nTime –; 
                    if( m_nTime <= 0 )                       //如果遊戲超時 
                        setState(GAME_END); 
                    break; 
                } 
    } 
     
    private void Collides(){                            //碰撞檢測 
        for( int n = 0; n < m_Goods.length; n ++ ){ 
            if( m_Chick.collidesWith(m_Goods[n]) ) 
            {//如果小雞與物品發生碰撞,即小雞接到瞭物品 
                switch( m_Goods[n].getType() ){ 
                case GoodsSprite.GODDS_GOLD:            //接到金元寶 
                    m_nScore += 5;                      //增加5個積分點 
                    break; 
                case GoodsSprite.GODDS_DIAMOND:         //接到鉆石 
                    m_nScore += 10;                     //增加10個積分點 
                    break; 
                case GoodsSprite.GODDS_FRUIT:           //接到圓形水果會被砸倒 
                    m_Chick.setState( ChickSprite.CHICK_DOWN ); 
                    break; 
                } 
                m_Goods[n].setVisible(false);           //讓物品消失 
            } 
        } 
    } 
    private void CreateGoods(){                     //隨機產生新物品 
        //以1比20的概率產生新物品 
        int rand = m_Random.nextInt() % 10;             //rand在-10~10之間 
        if( rand != 0 )                          
            return; 
        for( int n = 0; n < m_Goods.length; n ++ ){ 
            if( m_Goods[n].isVisible() == false ){ 
                //隨機設置新物品的種類及初始位置 
                int type = Math.abs( m_Random.nextInt()); 
                type = type % GoodsSprite.GODDS_TYPE_NUM; 
                m_Goods[n].setType(type); 
                 
                int x = m_Random.nextInt() % (screenWidth-screenStartX-10); 
                x = Math.abs(x)+screenStartX; 
                m_Goods[n].StartDrop( x,screenStartY+10); 
                break; 
            } 
        } 
    } 
    public void doDraw() 
    { 
        Canvas c = null; 
        try 
        { 
        c = holder.lockCanvas(); 
        synchronized (holder) { 
 
            paint(c); 
        } 
        }finally{ 
            if(c != null) 
            { 
            holder.unlockCanvasAndPost(c); 
            } 
        } 
    } 
    //畫圖 
    public void paint(Canvas canvas) 
    { 
        //用黑色清屏 
        Paint backpaint = new Paint(); 
        backpaint.setColor(Color.BLACK); 
        canvas.drawRect(0, 0, getWidth(), getHeight(), backpaint); 
         
        Paint forePaint = new Paint(); 
        forePaint.setColor(Color.RED); 
        forePaint.setTextSize(20); 
        switch( m_nState ){ 
        case GAME_UI:                                   //顯示標題界面 
            m_UI.Paint(canvas, forePaint,getWidth(), getHeight()); 
            break; 
        case GAME_GAMING:                               //顯示遊戲畫面 
            m_Back.Paint(canvas, forePaint,getWidth(), getHeight()); 
            m_Chick.paint(canvas,forePaint); 
            for( int n = 0; n < m_Goods.length; n ++ ) 
                m_Goods[n].paint(canvas,forePaint); 
            //顯示文字信息 
            StringBuffer strText = new StringBuffer(); 
            strText.append("Time:"); 
            strText.append(m_nTime / 10); 
            strText.append("     Score:"); 
            strText.append(m_nScore); 
            canvas.drawText( strText.toString(),20,20,forePaint); 
            break; 
        case GAME_END:                                  //顯示結束信息 
            m_Back.Paint(canvas,forePaint, getWidth(), getHeight()); 
            StringBuffer strEndText = new StringBuffer(); 
            strEndText.append("遊戲結束,本次得分:"); 
            strEndText.append(m_nScore); 
            canvas.drawText( strEndText.toString(), 20, getHeight()/2,forePaint ); 
            break; 
        } 
    } 
    @Override 
    public void surfaceChanged(SurfaceHolder holder, int format, int width, 
            int height) { 
        // TODO Auto-generated method stub 
 
         
    } 
    @Override 
    public void surfaceCreated(SurfaceHolder holder) { 
        // TODO Auto-generated method stub 
        initView(); 
        start(); 
     
    } 
    @Override 
    public void surfaceDestroyed(SurfaceHolder holder) { 
        // TODO Auto-generated method stub 
        stop(); 
         
    } 
     
    float x1 = 0; 
    float x2 = 0; 
    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
        // TODO Auto-generated method stub   
        switch(event.getAction()) 
        { 
        case MotionEvent.ACTION_DOWN: 
            setKeyStates(GameView.ACTION_FIRE); 
            x1 = event.getX(); 
            x2 = 0; 
            break; 
        case MotionEvent.ACTION_UP: 
            x2 =event.getX(); 
            if(x2-x1>50) 
            { 
                setKeyStates(GameView.ACTION_RIGHT); 
            }else if(x1-x2>50) 
            { 
                setKeyStates(GameView.ACTION_LEFT); 
            } 
            x1= 0; 
            x2 = 0; 
            break; 
        default : 
            break; 
        } 
        return true; 
    } 
 
 
     
     

作者“漢堡的博客”
 

發佈留言