实现贪吃蛇

来源:互联网 发布:简单c语言代码 编辑:程序博客网 时间:2024/06/09 21:28

贪吃蛇:

1.它的移动我们采用头部加一个尾巴减一个

2.我们将View的大小分成很多个格子

3.蛇的移动是以一个格子为单位



/** * Created by Administrator on 2016/10/11. */public class GameView extends View {    //用了存放蛇的身体所在格子    LinkedList<Point> body = new LinkedList<>();    //用了保存每个小格子的size    public static final int SIZE = 30;    Paint paint;   //表示是否在运行   private boolean isRun = true;   //这里用了记录它将要移动的方向    private int orentation = DOWN;   //这里记录上次移动的方向   private int lastOrentation = DOWN;    public static int UP = 1;    public static int DOWN = -1;    public static int LEFT = -2;    public static int RIGHT = 2;   //这个点是将要移动到的那个坐标   private Point currentPoint = new Point();   //生产蛋的坐标   private Point food;    int height;    int width;    Random random = new Random();    ExecutorService thread = Executors.newSingleThreadExecutor();    boolean isPause;   //这里用了暂停线程用到   Lock lock = new ReentrantLock();    Condition condition = lock.newCondition();    //要跟新上去的界面    TextView textView;    //记录的得分    int score;    public GameView(Context context) {        this(context,null);    }    public GameView(Context context, AttributeSet attrs) {        super(context, attrs);        initData();    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        paint.setColor(Color.GREEN);        //初始化蛇的身体        for (Point point : body) {            canvas.drawRect(point.x * SIZE, point.y * SIZE, point.x * SIZE + SIZE - 1, point.y * SIZE + SIZE - 1, paint);        }        paint.setColor(Color.RED);        //绘画食物        canvas.drawRect(food.x * SIZE, food.y * SIZE, food.x * SIZE + SIZE, food.y * SIZE + SIZE, paint);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        if (width == 0) {            width = getMeasuredWidth();            height = getMeasuredHeight();            createFood();        }    }    private void initData() {        paint = new Paint();        paint.setAntiAlias(true);        paint.setColor(Color.GRAY);        createBody();        startGame();    }    private void createBody() {        for (int i = 5; i < 10; i++) {            body.add(new Point(i, 5));        }    }    public void setOrentation(int orentation) {        this.orentation = orentation;    }    //运行游戏    private void startGame() {        new Thread(new Runnable() {            @Override            public void run() {                while (isRun) {                        move();                        postInvalidate();                        try {                            Thread.sleep(300);                        } catch (Exception e) {                            e.printStackTrace();                        }                        if(isPause){                            lock.lock();                            try{                                condition.await();                            }catch (Exception e){                               e.printStackTrace();                            } finally {                                lock.unlock();                            }                        }                }            }        }).start();    }    private void move() {        if (orentation == -lastOrentation) {//当前方向与上次相反就不予改变            orentation = lastOrentation;        } else {            lastOrentation = orentation;        }        Point head = body.getFirst();        switch (orentation) {            case 1://向上移动                currentPoint.set(head.x, head.y - 1);                break;            case -1://向下移动                currentPoint.set(head.x, head.y + 1);                break;            case 2://向右移动                currentPoint.set(head.x + 1, head.y);                break;            case -2://向左移动                currentPoint.set(head.x - 1, head.y);                break;        }        if (!canRun(head)) {            DataUtils.saveMaxScore(getContext(),score);            textView.post(new Runnable() {                @Override                public void run() {                    showDailog();                }            });            return;        }        //头部加1        body.addFirst(currentPoint);        if (currentPoint.equals(food)) {            currentPoint = food;            food = null;            score+=10;           textView.post(new Runnable() {               @Override               public void run() {                   textView.setText("当前的得分:"+score);               }           });            createFood();        } else { //尾巴减一并且复用尾巴的坐标            currentPoint = body.removeLast();        }    }    //创建食物    public void createFood() {        thread.execute(new Runnable() {            @Override            public void run() {                do {                    int x = random.nextInt(width / SIZE);                    int y = random.nextInt(height / SIZE);                    if (food == null)                        food = new Point(x, y);                    else {                        food.set(x, y);                    }                } while (body.contains(food));            }        });    }    //判断是否能继续游戏    public boolean canRun(Point head) {        //下一步运行不能咬到自己        if (body.contains(currentPoint) && !body.getLast().equals(currentPoint)) {            isRun = false;            return false;        }        //运行不能越界        if (head.x < 0) {            isRun = false;            return false;        }        if (head.y < 0) {            isRun = false;            return false;        }        if (width != 0) {            if (head.x > width / SIZE-1) {                isRun = false;                return false;            }            if (head.y > height / SIZE-2) {                isRun = false;                return false;            }        }        return true;    }    //停止游戏    public void stopGame(){        isRun = false;        thread.shutdownNow();    }    //暂停    public void setPause(){        isPause = true;    }    //继续    public void continueGame(){        if(!isPause)            return;        lock.lock();        try{            condition.signal();            isPause = false;        }finally {            lock.unlock();        }    }    public void setTextView(TextView textView){        this.textView = textView;    }    //弹出对话框    public void showDailog(){        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());        builder.setTitle("GAVE OVER");        builder.setMessage("很遗憾,是否继续挑战");        builder.setPositiveButton("继续", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                restart();            }        });        builder.setNegativeButton("放弃", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {               dialog.dismiss();            }        });        builder.create().show();    }    //重写开始    public void restart(){        isRun = false;       lastOrentation =  orentation = DOWN;        score = 0;        body.clear();        createBody();        createFood();        isRun = true;        startGame();    }}

0 0
原创粉丝点击