安卓版传感器利用之带体感操作的打砖块小游戏

创建一个名为HitBall-master的项目

Ball类:主要是进行打向砖块的球进行的绘制,以及最开始的位置的定义

部分代码如下:

//发射坐标
public void shot(int x, int y) {
mSpeed.x = x;
mSpeed.y = y;
}

//绘制圆
public void draw(Canvas canvas) {
canvas.drawCircle(mCenter.x, mCenter.y, mRadius, mPaint);
mCenter.offset(mSpeed.x, mSpeed.y);
}

//设置绘制位置
public void setPosition(int x, int y) {
mCenter.x = x;
mCenter.y = y;
}



public Bat() {
mPaint = new Paint();
mPaint.setColor(Color.MAGENTA);
mSpeed = DEFAULT_SPEED;
mWidth = DEFAULT_WIDTH;
}

//左移
public void moveLeft() {
mBody.offset(-mSpeed, 0);
}
//右移
public void moveRight() {
mBody.offset(mSpeed, 0);
}
//绘制板
public void draw(Canvas canvas) {
canvas.drawRect(mBody, mPaint);
}
//设置位置
public void setBodyPosition(Rect body) {
mBody = body;
}

Brick类:绘制砖块,实现砖块的颜色随机变化,以及砖块的生命周期:碰撞后颜色改变,以及最终 的消失

部分代码如下:


//砖块颜色
private static int[] sBloodColors = {
Color.RED, Color.YELLOW, Color.GREEN
};

//定义砖块
public Brick(int row, int col, int width, int height, int blood) {
int left = col * width + BRICK_GAP / 2;
int right = left + width - 3 * BRICK_GAP / 2;
int top = row * height + BRICK_GAP;
int bottom = top + height - BRICK_GAP;
mBody = new Rect(left, top, right, bottom);
mBlood = blood;
this.row = row;
this.col = col;
}

//砖块绘制
@Override
public void draw(Canvas canvas) {
mPaint.setColor(sBloodColors[mBlood]);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawRect(mBody, mPaint);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(mBody.left + BRICK_BORDER,
mBody.top + BRICK_BORDER,
mBody.right - BRICK_BORDER,
mBody.bottom - BRICK_BORDER,
mPaint);
}

//判断砖块数(碰撞则减一)
@Override
public boolean hit() {
mBlood--;
return mBlood < 0;
}

Table类:判断砖块打击的位置以及应该做出的相应反应,添加了背景音乐,

部分代码如下

//音乐加载
private void loadSound(Context context) {
mSoundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
mAssetManager = context.getAssets();
try {
String[] filenames = mAssetManager.list("sounds");
for (String filename : filenames) {
AssetFileDescriptor fd = mAssetManager.openFd("sounds/" + filename);
int soundId = mSoundPool.load(fd, 0);
mSounds.add(soundId);
}
} catch (IOException e) {
e.printStackTrace();
}
}

//更新关卡
private void loadLevel() {
//初始化数组,20行,5列
mCells = new Cell[ROW_NUM][COL_NUM];
mCellWidth = mBoundary.width() / COL_NUM;
mCellHeight = mBoundary.height() / ROW_NUM;
try {
String[] filenames = mAssetManager.list("levels");
// TODO: 应该根据关卡加载
String filename = filenames[0];
loadLevel(filename);
} catch (IOException e) {
e.printStackTrace();
}
}

private void loadLevel(String filename) {
try {
InputStream inputStream = mAssetManager.open("levels/" + filename);
BufferedReader reader =
new BufferedReader(new InputStreamReader(inputStream));
String line;
int row = 0;
Paint paint = new Paint();
while ((line = reader.readLine()) != null) {
String[] cells = line.split(",");
for (int col = 0; col < cells.length; col++) {
String cell = cells[col];
if (cell.equals("x")) {
int blood = (int) (Math.floor(Math.random() * 3));
//绘制砖块
Cell brick = new Brick(row, col, mCellWidth, mCellHeight, blood);
brick.setPaint(paint);
mCells[row][col] = brick;
}
}
row++;
}
} catch (IOException e) {
e.printStackTrace();
}
}

//设置球体
public void setBall(Ball ball) {
mBall = ball;
mBall.setRadius(mBoundary.width() / 20);
}
//设置球板
public void setBat(Bat bat) {
mBat = bat;
mBat.setWidth(mBoundary.width() / 3);
}

public void showGameOver() {
mShowGameOver = true;
mBall.stop();
}

public void showGamePass() {
mShowGamePass = true;
mBall.stop();
}

public void draw(Canvas canvas) {
canvas.drawColor(Color.LTGRAY);
if (mShowGameOver) {
canvas.drawText("Game Over!", mBoundary.centerX() - 218, mBoundary.centerY(), mPaintGameOver);
} else if (mShowGamePass) {
canvas.drawText("过关了!", mBoundary.centerX() - 168, mBoundary.centerY(), mPaintGameOver);
}
// 绘制边界
canvas.drawPath(mBoundaryPath, mPaintBoundary);

// 绘制砖块
for (int row = 0; row < ROW_NUM; row++) {
for (int col = 0; col < COL_NUM; col++) {
Cell cell = mCells[row][col];
if (cell != null) {
cell.draw(canvas);
}
}
}

// 判断球是否和边界碰撞(碰撞则改变移动的x.y为相反值)
int hitType = getHitType();
if ((hitType & (HIT_TOP | HIT_BOTTOM)) > 0) {
mBall.reverseYSpeed();
}
if ((hitType & (HIT_LEFT | HIT_RIGHT)) > 0) {
mBall.reverseXSpeed();
}
if (isBatHit() && mBall.isToBottom()) {
mBall.reverseYSpeed();
}
mBall.draw(canvas);

moveBat();
mBat.draw(canvas);
}

//是否球与板是否碰撞
private boolean isBatHit() {
Point c = mBall.getCenter();
float r = mBall.getRadius();
Rect batBody = mBat.getBody();
if (c.x >= batBody.left && c.x <= batBody.right) {
if (c.y - r < batBody.bottom && c.y + r > batBody.top) {
return true;
}
}
return false;
}

//获取球与球板的碰撞类型
private int getHitType() {
int type = HIT_NONE;
Point c = mBall.getCenter();
float r = mBall.getRadius();
int row = c.y / mCellHeight;
int col = c.x / mCellWidth;
Cell cell = null;
boolean hitCell = false;
Rect body = null;
boolean ballInTable = mBoundary.contains(c.x, c.y);
// 判断撞头
if (ballInTable && row > 0) {
cell = mCells[row - 1][col];
if (cell != null) {
body = cell.getBody();
hitCell = c.y > body.bottom && c.y - r <= body.bottom;
if (hitCell) {
playHitBrickSound(cell);
if (cell.hit()) {
mCells[cell.row][cell.col] = null;
}
}
}
}
if (mBall.isToTop() && (c.y - r <= 0 || hitCell)) {
type |= HIT_TOP;
}
// 判断撞右边
hitCell = false;
if (ballInTable && col < COL_NUM - 1) {
cell = mCells[row][col + 1];
if (cell != null) {
body = cell.getBody();
hitCell = c.x < body.left && c.x + r >= body.left;
if (hitCell) {
playHitBrickSound(cell);
if (cell.hit()) {
mCells[cell.row][cell.col] = null;
}
}
}
}
if (mBall.isToRight() &&
(c.x + r >= mBoundary.right && c.y < mBoundary.bottom || hitCell)) {
type |= HIT_RIGHT;
}
// 判断撞左边
hitCell = false;
if (ballInTable && col > 0) {
cell = mCells[row][col - 1];
if (cell != null) {
body = cell.getBody();
hitCell = c.x > body.right && c.x - r <= body.right;
if (hitCell) {
playHitBrickSound(cell);
if (cell.hit()) {
mCells[cell.row][cell.col] = null;
}
}
}
}
if (mBall.isToLeft() &&
((c.x - r <= 0 && c.y < mBoundary.bottom) || hitCell)) {
type |= HIT_LEFT;
}
// 判断撞下边
if (ballInTable && row < ROW_NUM - 1) {
cell = mCells[row + 1][col];
if (cell != null) {
body = cell.getBody();
hitCell = c.y < body.top && c.y + r >= body.top;
if (hitCell) {
playHitBrickSound(cell);
if (cell.hit()) {
mCells[cell.row][cell.col] = null;
}
}
}
}
if (mBall.isToBottom() && hitCell) {
type |= HIT_BOTTOM;
}
return type;
}

//设置碰撞音乐
private void playHitBrickSound(Cell cell) {
mSoundPool.play(mSounds.get(cell.getBlood()), 1f, 1f, 0, 0, 1);
}

// 移动板
public void moveBat() {
if (isBatMoving) {
if (isBatMoveToLeft) {
// 板左移动
if (mBat.getBody().left > mBoundary.left) mBat.moveLeft();
} else {
// 板右移动
if (mBat.getBody().right < mBoundary.right) mBat.moveRight();
}
}
}

//通过触摸事件移动板
public void startBatMove(MotionEvent e) {
if (mBoundary.contains((int) e.getX(), (int) e.getY())) {
isBatMoving = true;
if (e.getX() > mBoundary.centerX()) { // move right
if (mBat.getBody().right < mBoundary.right) isBatMoveToLeft = false;
} else {
if (mBat.getBody().left > mBoundary.left) isBatMoveToLeft = true;
}
}
}


public void startBatMove(double roll) {
if (isBatMoving) {
if (isBatMoveToLeft) {
if (roll < 8 && roll > -10) {
isBatMoving = false;
} else if (roll <= -10) {
isBatMoveToLeft = true;
}
} else {
if (roll > -8 && roll < 10) {
isBatMoving = false;
} else if (roll >= 10) {
isBatMoveToLeft = false;
}
}
} else {
if (roll <= -10) {
isBatMoving = true;
isBatMoveToLeft = true;
} else if (roll >= 10) {
isBatMoving = true;
isBatMoveToLeft = false;
}
}
}

// 通过倾斜度改变板的形状
public void changeBatBody(double pitch) {
Rect body = mBat.getBody();
boolean wider = body.width() == mBoundary.width(); //板和边界宽度是否一致
boolean higher = body.height() > mNormalBatBody.height();//板是否比正常板的高度高
if (wider) {
if (pitch > -25) {//倾斜度判断
body.left = mNormalBatBody.left;
body.right = mNormalBatBody.right;
}
} else {
if (pitch < -30) {
body.left = mBoundary.left;
body.right = mBoundary.right;
}
}
if (higher) {
if (pitch < 10) {
body.top = mNormalBatBody.top;
}
} else {
if (pitch > 15) {
body.top = body.bottom - 10 * body.height();
}
}
}

public void stopBatMove() {
isBatMoving = false;
}

// 重置body和球
public void reset() {
int left = mBoundary.centerX() - mBat.getWidth() / 2;
int top = mBoundary.bottom - Bat.DEFAULT_HEIGHT;
int right = mBoundary.centerX() + mBat.getWidth() / 2;
int bottom = mBoundary.bottom;
// 绘制body
Rect body = new Rect(left, top, right, bottom);
mNormalBatBody = new Rect(body);
// 设置body位置
mBat.setBodyPosition(body);
// 设置球位置
mBall.setPosition(mBoundary.centerX(), (int) (top - mBall.getRadius()));
mBall.stop();
loadLevel();
mShowGameOver = false;
mShowGamePass = false;
}

//射击球
public void shotBall() {
mBall.shot(20, -20);
}

//是否球出界
public boolean isBallOutside() {
Point c = mBall.getCenter();
return c.y - 100 > mBoundary.bottom;
}

// 是否还有砖块
public boolean hasNoneBrick() {
for (int row = 0; row < ROW_NUM; row++) {
for (int col = 0; col < COL_NUM; col++) {
Cell cell = mCells[row][col];
if (cell instanceof Brick) {
return false;
}
}
}
return true;
}
}

GameView类:利用安卓的传感器操作随着手机的倾斜角度实现打砖块的带体感操作

部分代码如下:

/**
* 第一步:获得传感器管理器
* 第二步:为具体的传感器注册监听器
* 第三步:实现具体的监听方法
* public void onSensorChanged(SensorEvent event) {}
public void onAccuracyChanged(Sensor sensor ,int accuracy ){}
*/

public class GameView extends SurfaceView implements Runnable, SurfaceHolder.Callback,
SensorEventListener {
//游戏状态常量
public static int STATE_READY = 1;
public static int STATE_PLAY = 2;
public static int STATE_PASS = 3;
public static int STATE_OVER = 4;

private int mState;

private Table mTable;
private Ball mBall;
private Bat mBat;

private boolean mIsRunning;
private GestureDetector mGestureDetector;
private SensorManager mSensorManager;

public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
//实例化手势识别对象
mGestureDetector = new GestureDetector(getContext(), new GameGestureDetector());
//实例化传感器管理对象
mSensorManager = (SensorManager) context.getSystemService(context.SENSOR_SERVICE);

//设置旋转向量传感器
Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
//监听传感器改变的采样率是否为适合游戏的速率
boolean ok = mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);

Log.d("mytag", "ok = " + ok);
Log.d("mytag", "sensor = " + sensor);

//实例化窗口管理器
WindowManager windowManager = (WindowManager) context.getSystemService(context.WINDOW_SERVICE);

//实例化矩形
Rect screenRect = new Rect();

windowManager.getDefaultDisplay().getRectSize(screenRect);

mTable = new Table(context, screenRect);
mBall = new Ball();
mTable.setBall(mBall);
mBat = new Bat();
mTable.setBat(mBat);
mTable.reset();
mState = STATE_READY;
}

//判断触摸事件
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: //单点触碰
case MotionEvent.ACTION_MOVE: //触摸点移动动作
if (mIsRunning && mState == STATE_PLAY) {
//当状态为STATE_PLAY球开始移动(mIsRunning mState同为1)
mTable.startBatMove(event);
}
break;
case MotionEvent.ACTION_UP: //单点触摸离开动作
mTable.stopBatMove();
break;
}
mGestureDetector.onTouchEvent(event);
return true;
}

//监听传感器的值变化
@Override
public void onSensorChanged(SensorEvent event) {
//
if (!mIsRunning || mState != STATE_PLAY) return;
int sensorType = event.sensor.getType(); //存储传感器类型
float[] rotationMatrix;
switch (sensorType) {
case Sensor.TYPE_ROTATION_VECTOR: //为旋转矢量传感器(代表设备的方向)
rotationMatrix = new float[16];
SensorManager.getRotationMatrixFromVector(rotationMatrix, event.values);
float[] orientationValues = new float[3];
SensorManager.getOrientation(rotationMatrix, orientationValues);
//倾斜度获取
double pitch = Math.toDegrees(orientationValues[1]);
double roll = Math.toDegrees(orientationValues[2]);
Log.e("mytag", "pitch = " + pitch + ", roll = " + roll);

//球板移动
mTable.startBatMove(roll);
//改变球板大小
mTable.changeBatBody(pitch);
break;

}
}

main类:加载mGameView

部分代码:

 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mGameView = new GameView(this, null);
setContentView(mGameView);
}
}

程序运行截图:

程序结果截图1
程序运行结果2
程序截图结果3

总结:这次实验使得我对画布更加了解,还有就是那个安卓传感器的使用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容