安卓打飞机源码分享

MainActivity

package com.example.matt.aircraft;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;

import com.example.matt.aircraft.DaFeiJiGameView;

import static android.content.ContentValues.TAG;

public class MainActivity extends Activity implements DialogInterface.OnClickListener{

    DaFeiJiGameView view = null;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        view = new DaFeiJiGameView(this);
//        view.setwindow(getWindowManager());
        setContentView(view);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            view.stop();
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("老哥再来一把?");
            alert.setNeutralButton("不打了", this);
            alert.setNegativeButton("接着干", this);
            alert.create().show();
            return false;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (which == -2) {
            onRestart();
        } else {
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }


}

DaFeiJiGameView

package com.example.matt.aircraft;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;

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

import static android.content.ContentValues.TAG;

public class DaFeiJiGameView extends SurfaceView implements SurfaceHolder.Callback, Runnable,
        View.OnTouchListener, View.OnClickListener {

    private Bitmap my;
    private Bitmap baozha;
    private Bitmap bg;
    private Bitmap diren;
    private Bitmap zidan;
    private Bitmap erjihuancun;
    //    private WindowManager windowManager;
    private int display_w;
    private int display_h;
    private ArrayList gameImages = new ArrayList<>();
    private ArrayList zidans = new ArrayList<>();



    public DaFeiJiGameView(Context context) {
        super(context);
        getHolder().addCallback(this);
        this.setOnTouchListener(this); // 事件注册
    }
//        // 得到屏幕的宽高
//        display_w = ;
//        display_h = ;

    private SoundPool pool = null;
    private int sound_bomb = 0;
    private int sound_gameover = 0;
    private int sound_shot = 0;

    private void init() {
        // 加载照片
        my = BitmapFactory.decodeResource(getResources(), R.drawable.my);
        baozha = BitmapFactory.decodeResource(getResources(), R.drawable.baozha);
        bg = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
        diren = BitmapFactory.decodeResource(getResources(), R.drawable.diren);
        zidan = BitmapFactory.decodeResource(getResources(), R.drawable.zidan);

        // 生产二级缓存照片
        erjihuancun = Bitmap.createBitmap(display_w, display_h, Bitmap.Config.ARGB_8888);

        gameImages.add(new BeijingImage(bg)); // 加入背景照片
        gameImages.add(new FeijiImage(my)); // 加入飞机照片
        gameImages.add(new DijiImage(diren, baozha));

        // 加载声音
        pool = new SoundPool(3, AudioManager.STREAM_SYSTEM, 5);

        sound_bomb = pool.load(getContext(), R.raw.bomb, 1);
        sound_gameover = pool.load(getContext(), R.raw.gameover, 1);
        sound_shot = pool.load(getContext(), R.raw.shot, 1);

    }

    @Override
    public void onClick(View v) {

    }

    private class SoundPlay extends Thread {
        int i = 0;
        public SoundPlay(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            pool.play(i, 1, 1, 1, 0, 1);
        }
    }

    private interface GameImage {
        public Bitmap getBitmap();

        public int getX();

        public int getY();


    }

    private class Zidan implements GameImage {

        private int x;
        private int y;
        private Bitmap zidan;
        private FeijiImage feiji;

        public Zidan(FeijiImage feiji, Bitmap zidan) {
            this.feiji = feiji;
            this.zidan = zidan;

            // 子弹居中
            x = feiji.getX() + feiji.getWidth() / 2 - 13;
            y = feiji.getY();
        }

        @Override
        public Bitmap getBitmap() {
            y -= 10;
            if (y <= -10) {
                zidans.remove(this);
            }
            return zidan;
        }

        @Override
        public int getX() {
            return x;
        }

        @Override
        public int getY() {
            return y;
        }
    }

    // 敌机
    private class DijiImage implements GameImage {
        private Bitmap diren;
        private int x;
        private int y;
        private int width;
        private int height;

        private List bitmaps = new ArrayList<>();

        public List getBaozhas() {
            return baozhas;
        }

        private List baozhas = new ArrayList<>();

        public DijiImage(Bitmap diren, Bitmap baozha) {
            this.diren = diren;
            bitmaps.add(Bitmap.createBitmap(diren, 0, 0, diren.getWidth() / 4, diren.getHeight()));
            bitmaps.add(Bitmap.createBitmap(diren, diren.getWidth() / 4 * 1, 0, diren.getWidth() / 4, diren.getHeight()));
            bitmaps.add(Bitmap.createBitmap(diren, diren.getWidth() / 4 * 2, 0, diren.getWidth() / 4, diren.getHeight()));
            bitmaps.add(Bitmap.createBitmap(diren, diren.getWidth() / 4 * 3, 0, diren.getWidth() / 4, diren.getHeight()));

            baozhas.add(Bitmap.createBitmap(baozha, 0, 0, baozha.getWidth() / 4, baozha.getHeight() / 2));
            baozhas.add(Bitmap.createBitmap(baozha, baozha.getWidth() / 4 * 1, 0, baozha.getWidth() / 4, baozha.getHeight() / 2));
            baozhas.add(Bitmap.createBitmap(baozha, baozha.getWidth() / 4 * 2, 0, baozha.getWidth() / 4, baozha.getHeight() / 2));
            baozhas.add(Bitmap.createBitmap(baozha, baozha.getWidth() / 4 * 3, 0, baozha.getWidth() / 4, baozha.getHeight() / 2));
            baozhas.add(Bitmap.createBitmap(baozha, 0, baozha.getHeight() / 2, baozha.getWidth() / 4, baozha.getHeight() / 2));
            baozhas.add(Bitmap.createBitmap(baozha, baozha.getWidth() / 4 * 1, baozha.getHeight() / 2, baozha.getWidth() / 4, baozha.getHeight() / 2));
            baozhas.add(Bitmap.createBitmap(baozha, baozha.getWidth() / 4 * 2, baozha.getHeight() / 2, baozha.getWidth() / 4, baozha.getHeight() / 2));
            baozhas.add(Bitmap.createBitmap(baozha, baozha.getWidth() / 4 * 3, baozha.getHeight() / 2, baozha.getWidth() / 4, baozha.getHeight() / 2));

            width = diren.getWidth() / 4;
            height = diren.getHeight();

            // 敌人出现的范围
            Random ran = new Random();
            x = ran.nextInt(display_w - width);
            y = -diren.getHeight();
        }

        private int index = 0;
        private int num = 0;

        @Override
        public Bitmap getBitmap() {
            Bitmap bitmap = bitmaps.get(index);
            if (num == 2) {
                index++;
                if (index == 8 && status) {
                    gameImages.remove(this);
                }
                if (index == bitmaps.size()) {
                    index = 0;
                }
                num = 0;
            }
            y += 10;
            num++;
            if (y > display_h) {
                gameImages.remove(this);
            }
            return bitmap;
        }

        private boolean status = false;

//        public void collide(ArrayList dijiImages) {
//            for (DijiImage diji : dijiImages) {
//                if (diji.getX() >= x && diji.getX() <= x + width && diji.getY() >= y && diji.getY() <= y +height ||
//                        x >= diji.getX() && x <= diji.getX() + diji.getWidth() && y >= diji.getY() && y <= diji.getY() + height) {
//                    life -= 10;
//                }
//            }
//        }


        // 受到攻击
        public void shoudaogongji(ArrayList zidans) {

            if (!status) {

                for (Zidan zidan : (List) zidans.clone()) {

                    if (zidan.getX() > x && zidan.getY() > y &&
                            zidan.getX() < x + width &&
                            zidan.getY() < y + height) {
                        zidans.remove(zidan);
                        status = true;
                        bitmaps = baozhas;
                        fenshu += 10;
                        new SoundPlay(sound_bomb).start();
                        break;
//                    Log.i(TAG, "击中");
                    }

                }
            }

        }


        @Override
        public int getX() {
            return x;
        }

        @Override
        public int getY() {
            return y;
        }


        public int getWidth() {
            return width;
        }

        public int getHeight() {
            return height;
        }
    }

    // 飞机图片
    private class FeijiImage implements GameImage {

        private Bitmap my;

        private int x;
        private int y;
        private int width;
        private int height;


        private List bitmaps = new ArrayList<>();

        private FeijiImage(Bitmap my) {
            this.my = my;
            bitmaps.add(Bitmap.createBitmap(my, 0, 0, my.getWidth() / 4, my.getHeight()));
            bitmaps.add(Bitmap.createBitmap(my, my.getWidth() / 4 * 1, 0, my.getWidth() / 4, my.getHeight()));
            bitmaps.add(Bitmap.createBitmap(my, my.getWidth() / 4 * 2, 0, my.getWidth() / 4, my.getHeight()));
            bitmaps.add(Bitmap.createBitmap(my, my.getWidth() / 4 * 3, 0, my.getWidth() / 4, my.getHeight()));

            width = my.getWidth() / 4;
            height = my.getHeight();

            x = (display_w - my.getWidth() / 4) / 2;
            y = display_h - my.getHeight() - 20;
        }

        private int index = 0;
        private int num = 0;

        @Override
        public Bitmap getBitmap() {
            Bitmap bitmap = bitmaps.get(index);
            if (num == 5) {
                index++;
                if (index == bitmaps.size()) {
                    index = 0;
                }
                num = 0;
            }
            num++;
            if (y > display_h) {
                gameImages.remove(this);
            }
            return bitmap;
        }

        // 飞机的生命值
        private int life = 100;

//        public void collide(ArrayList dijiImages) {
//            for (DijiImage diji : dijiImages) {
//                if ((diji.getX() >= x && diji.getX() <= x + width && diji.getY() >= y && diji.getY() <= y +height) ||
//                        (x >= diji.getX() && x <= diji.getX() + diji.getWidth() && y >= diji.getY() && y <= diji.getY() + height)) {
//                    setLife(getLife() - 10);
////                    Log.d("tag", "发生碰撞");
//                }
//            }
//        }

        public void collide(DijiImage diji) {
//            Log.d("tag", "碰撞检测");
                if (diji.getX() >= x && diji.getX() <= x + width && diji.getY() >= y && diji.getY() <= y +height ||
                        x >= diji.getX() && x <= diji.getX() + diji.getWidth() && y >= diji.getY() && y <= diji.getY() + height) {
                    if (getLife() <= 0) {
                        gameover();
                    }
                    if (getLife() >= 10)
                    setLife(getLife() - 10);

                    diji.bitmaps = diji.getBaozhas();
                    // TODO 添加爆炸
                    gameImages.remove(diji);
                    new SoundPlay(sound_bomb).start();
//                    Log.d("tag", "发生碰撞");

                }
        }

        @Override
        public int getX() {
            return x;
        }

        @Override
        public int getY() {
            return y;
        }


        public void setX(int x) {
            // 保证飞机不越界
            if (x >= 0 && x <= display_w - width) {
                this.x = x;
            }
        }


        public void setY(int y) {
            if (y >= 0 && y <= display_h - height) {
                this.y = y;
            }

        }

        public int getLife() {
            return life;
        }

        public void setLife(int life) {
            this.life = life;
        }

        public int getWidth() {
            return width;
        }

        public int getHeight() {
            return height;
        }
    }

    // 背景图片
    private class BeijingImage implements GameImage {
        private Bitmap bg;

        private BeijingImage(Bitmap bg) {
            this.bg = bg;
            newBitmap = Bitmap.createBitmap(display_w, display_h, Bitmap.Config.ARGB_8888);
        }

        private Bitmap newBitmap = null;
        private int height = 0;

        public Bitmap getBitmap() {
            Paint p = new Paint();
            Canvas canvas = new Canvas(newBitmap);

            canvas.drawBitmap(bg, new Rect(0, 0, bg.getWidth(), bg.getHeight()),
                    new Rect(0, height, display_w, display_h + height), p);

            canvas.drawBitmap(bg, new Rect(0, 0, bg.getWidth(), bg.getHeight()),
                    new Rect(0, -display_h + height, display_w, height), p);

            height++;
            if (height > display_h) {
                height = 0;
            }
            return newBitmap;
        }


        @Override
        public int getX() {
            return 0;
        }

        @Override
        public int getY() {
            return 0;
        }

    }

    private boolean status = false;
    private SurfaceHolder holder;
    private long fenshu = 0;
    private int life;

    private boolean stopState = false;
    public void stop() {
        stopState = true;
    }

    public void start() {
        stopState = false;
        thread.interrupt();
    }

    private boolean over = false;

    // 绘画中心
    @Override
    public void run() {
        Paint p1 = new Paint();
        Paint p2 = new Paint();
        p2.setColor(Color.WHITE);
        p2.setTextSize(50);
        p2.setDither(true);
        p2.setAntiAlias(true);
        int diren_num = 0;
        int zidan_num = 0;
        try {
            while (status) {
                while (stopState) {
                    try {
                        Thread.sleep(1000000);
                    } catch (Exception e) {

                    }
                }
                // 按住发子弹
                if (selectFeiji != null) {
                    if (zidan_num == 10) {
                        new SoundPlay(sound_shot).start();
                        zidans.add(new Zidan(selectFeiji, zidan));
                        zidan_num = 0;
                    }
                    zidan_num++;
                }

                Canvas newCanvas = new Canvas(erjihuancun);

                if (over) {
                    p2.setColor(Color.RED);
                    p2.setTextSize(200);
                    newCanvas.drawText("GAME OVER", 50, 50, p2);
                }

                // 碰撞检测
                for (GameImage image : (List) gameImages.clone()) {
                    if (image instanceof FeijiImage) {
                        FeijiImage feiji = (FeijiImage) image;
                        life = feiji.getLife();
//                        Log.d(TAG, "获得飞机");
                        for (GameImage image2 : (List) gameImages.clone()) {
                            if (image2 instanceof DijiImage) {
                                DijiImage diji = (DijiImage)image2;
//                                Log.d(TAG, "获得敌机");
                                feiji.collide(diji);
                            }
                        }
                    }
                }

                for (GameImage image : (List) gameImages.clone()) {

                    if (image instanceof DijiImage) {
                        // 把子弹告诉敌机
                        ((DijiImage) image).shoudaogongji(zidans);
                    }

                    newCanvas.drawBitmap(image.getBitmap(), image.getX(),
                            image.getY(), p1);
                }

                for (Zidan image : (List) zidans.clone()) {
                    newCanvas.drawBitmap(image.getBitmap(), image.getX(),
                            image.getY(), p1);
                }

                // 分数
                newCanvas.drawText("分数: " + fenshu, 0, 50, p2);
                newCanvas.drawText("生命: " + life, 0, 100, p2);



                if (diren_num == 10) {
                    diren_num = 0;
                    gameImages.add(new DijiImage(diren, baozha));
                }
                diren_num++;

                Canvas canvas = holder.lockCanvas();


                canvas.drawBitmap(erjihuancun, 0, 0, p1);
                holder.unlockCanvasAndPost(canvas);

                Thread.sleep(5);
            }
        } catch (Exception e) {

        }
    }

    private void gameover() {
        Log.d(TAG, "游戏结束了!");
        over = true;
        new SoundPlay(sound_gameover).start();
        try {
            Thread.sleep(1000000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


//
//        // TODO 这里有问题 炸了
//        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
//        dialog.setTitle("游戏结束");
//        dialog.setMessage("太差了,继续游戏?");
//        dialog.setCancelable(false);
//        dialog.setPositiveButton("接着干", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                new MainActivity();
//            }
//        });
//        dialog.setNegativeButton("不打了", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                android.os.Process.killProcess(android.os.Process.myPid());
//            }
//        });
//        dialog.create().show();
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        display_w = width;
        display_h = height;

        init();
        this.holder = holder;
        status = true;
        thread = new Thread(this);
        thread.start();

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        status = false;
    }

    Thread thread = null;
    FeijiImage selectFeiji;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // 手接近屏幕
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // 找到飞机图片
            for (GameImage image : gameImages) {
                if (image instanceof FeijiImage) {
                    FeijiImage feiji = (FeijiImage) image;
                    // 手触摸飞机
                    if (feiji.getX() < event.getX() && feiji.getY() < event.getY() &&
                            feiji.getX() + feiji.getWidth() > event.getX() &&
                            feiji.getY() + feiji.getHeight() > event.getY()) {
                        selectFeiji = feiji;
                    } else {
                        selectFeiji = null;
                    }
                    break;
                }
            }
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            if (selectFeiji != null) {
                // 手指触摸飞机中部位置
                selectFeiji.setX((int) event.getX() - selectFeiji.getWidth() / 2);
                selectFeiji.setY((int) event.getY() - selectFeiji.getHeight() / 2);
            }

        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            selectFeiji = null;
        }
        return true;
    }
}

安卓打飞机源码分享_第1张图片

安卓打飞机源码分享_第2张图片

你可能感兴趣的:(android)