android Snake(3)

添加两个苹果到主界面

Coordinate定义坐标,其中有能够判断是否相等的equals方法,用以判断两个坐标是否相等。MyRandom随机数生成类,封装random能够控制随机数产生的范围,产生随机坐标。SnakeView中判断产生的苹果是否重复,如果重复再产生一个,直到不重复为止。

Coordinate.java

package edu.hhxy.util;

public class Coordinate {
    public int row;
    public int column;

    public Coordinate(int row, int column) {
        super();
        this.row = row;
        this.column = column;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + column;
        result = prime * result + row;
        return result;
    }

    public boolean equals(Coordinate obj) {
        if (column != obj.column)
            return false;
        if (row != obj.row)
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Coordinate [row=" + row + ", column=" + column + "]";
    }
}

MyRandom.java

package edu.hhxy.util;

import java.util.Random;
public class MyRandom {
    public static Random RNG = new Random();
    public static int MAXROWS = 0;
    public static int MAXCOLUMNS = 0;
    //限定隨機數產生的範圍
    public void reset(int rows, int columns) {
        MAXROWS = rows;
        MAXCOLUMNS = columns;
    }
    //得到一個座標
    public Coordinate getCoordinate() {
        int newR = 1 + RNG.nextInt(MAXROWS - 2);
        int newC = 1 + RNG.nextInt(MAXCOLUMNS - 2);
        return new Coordinate(newR, newC);
    }
}

SnakeView

package edu.hhxy.view;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import edu.hhxy.mysnakegame.R;
import edu.hhxy.util.Coordinate;
import edu.hhxy.util.MyRandom;

public class SnakeView extends BasicView {
    private int mMode = READY;
    public static final int PAUSE = 0;
    public static final int READY = 1;
    public static final int RUNNING = 2;
    public static final int LOSE = 3;

    public static final int RED_STAR = 1;
    public static final int YELLOW_STAR = 2;
    public static final int GREEN_STAR = 3;
    public static final int BITMAP_ARRAY_SIZE = 4;

    private TextView mStatusText;
    private ArrayList<Coordinate> appleList = new ArrayList<Coordinate>();
    // //////////////////
    private long period = 500L;
    private long lastMove = 0L;

    @SuppressLint("HandlerLeak")
    class Refresh extends Handler {// 开启子线程,定时对界面刷新

        @Override
        public void handleMessage(Message msg) {
            SnakeView.this.update();
            SnakeView.this.invalidate();
            super.handleMessage(msg);
        }

        public void delayed(long times) {
            this.removeMessages(0);// 把栈顶消息清空
            sendMessageDelayed(obtainMessage(0), times);
        }
    }

    private Refresh gameFresh = new Refresh();

    // //////////////////

    public SnakeView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initGame();
    }

    public SnakeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initGame();
    }

    /*
     * 初始化SnakeView加载图片
     */
    private void initGame() {
        setFocusable(true);
        /* 调用父类方法设置bitMap大小 */
        resetBitmapArray(BITMAP_ARRAY_SIZE);
        /* 调用父类加載picture資源 */
        loadPicture(GREEN_STAR,
                this.getResources().getDrawable(R.drawable.greenstar));
        loadPicture(YELLOW_STAR,
                this.getResources().getDrawable(R.drawable.yellowstar));
        loadPicture(RED_STAR,
                this.getResources().getDrawable(R.drawable.redstar));
    }

    public void setTextView(TextView findViewById) {
        mStatusText = findViewById;
    }

    public void setMode(int newMode) {
        int oldMode = mMode;
        mMode = newMode;

        if (newMode == RUNNING & oldMode != RUNNING) {
            mStatusText.setVisibility(View.INVISIBLE);
            update();
            return;
        }
        CharSequence str = "";
        if (newMode == READY) {
            str = "Snake
 Press Up to Play";
        }
        if (newMode == LOSE) {
            str = "Game Over
";
        }

        mStatusText.setText(str);
        mStatusText.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent msg) {
        // 判断是否隐藏主界面,显示当前界面
        if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
            if (mMode == READY | mMode == LOSE) {
                initNewGame();
                setMode(RUNNING);
                update();
                return (true);
            }
            return (true);
        }
        return super.onKeyDown(keyCode, msg);
    }

    private void initNewGame() {
        appleList.clear();
        addRandomApple();
        addRandomApple();
    }

    private void addRandomApple() {
        MyRandom myRandom = new MyRandom();
        myRandom.reset(rows, columns);
        Coordinate coordinate = null;
        boolean collsion = false,found=false;
        while (!found) {
            coordinate = myRandom.getCoordinate();
            collsion = false;
            for (Coordinate c : appleList) {
                if (c.equals(coordinate)) {
                    collsion = true;
                }
            }
            found=!collsion;
        }
        appleList.add(coordinate);
        Log.d("SIZE",appleList.size()+"");
    }

    public void update() {
        if (mMode == RUNNING) {
            long now = System.currentTimeMillis();
            if (now - lastMove > period)// 如果当前时间离最近一次刷新的时间大于period,就刷新,同时更新lastMove
            {
                clearMaps();
                // 更新墙
                updateWalls();
                // 更新苹果
                updateApple();
                gameFresh.delayed(period);
                lastMove = now;
            }
        }
    }

    private void updateApple() {
        for (Coordinate c : appleList) {
            setMaps(YELLOW_STAR, c.row, c.column);
        }
    }

    /*
     * 初始墙
     */
    private void updateWalls() {
        for (int x = 0; x < columns; x++) {
            setMaps(GREEN_STAR, 0, x);
            setMaps(GREEN_STAR, rows - 1, x);
        }
        for (int y = 1; y < rows - 1; y++) {
            setMaps(GREEN_STAR, y, 0);
            setMaps(GREEN_STAR, y, columns - 1);
        }
        Log.d("freshed", "freshed wall");
    }
}

运行结果:

原文地址:https://www.cnblogs.com/jianfengyun/p/3767557.html