原來的貪喫蛇是在模擬機上運行的,需要按鍵去操控,而我呢,就是改寫在真機上運行的,用手指滑動控制
改寫代碼就是把原來的onkey()改爲ontoucheven()
代碼如下
@Override
public boolean onTouchEvent(MotionEvent e) {
// TODO Auto-generated method stub
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
startPoint.x = (int) e.getX();
startPoint.y = (int) e.getY();
break;
case MotionEvent.ACTION_UP:
endPoint.x = (int) e.getX();
endPoint.y = (int) e.getY();
actionCheck();
break;
}
return true;
}
public void actionCheck(){
//手指向上滑動
if (startPoint.y >endPoint.y && Math.abs(startPoint.y-endPoint.y)>Math.abs(startPoint.x-endPoint.x)) {
if (mMode == READY | mMode == LOSE) {
/*
* At the beginning of the game, or the end of a previous one,
* we should start a new game.
*/
initNewGame();
setMode(RUNNING);
update(); //update()實現了對遊戲數據的更新,是整個遊戲的推動力。
}
if (mMode == PAUSE) {
/*
* If the game is merely paused, we should just continue where
* we left off.
*/
setMode(RUNNING);
update();
}
if (mDirection != SOUTH) { //如果按鍵的方向 跟蛇本身的運動方向完全相反,則無法執行
mNextDirection = NORTH;
}
}
//手指向下滑動
if (startPoint.y <endPoint.y && Math.abs(startPoint.y-endPoint.y)>Math.abs(startPoint.x-endPoint.x)) {
if (mDirection != NORTH) {
mNextDirection = SOUTH;
}
}
//手指向左滑動
if (startPoint.x >endPoint.x && Math.abs(startPoint.y-endPoint.y)<Math.abs(startPoint.x-endPoint.x)) {
if (mDirection != EAST) {
mNextDirection = WEST;
}
}
//手指向右滑動
if (startPoint.x <endPoint.x && Math.abs(startPoint.y-endPoint.y)<Math.abs(startPoint.x-endPoint.x)) {
if (mDirection != WEST) {
mNextDirection = EAST;
}
}
一開始我想應該是用實現監聽接口的方法來實現控制,但是卻無法導入包,上網找也找不到原因所在,後來才用當前的辦法來解決
還有就是,startpoint 和endpoint沒有實例化,出現了NPE異常
我只是菜鳥,還要繼續努力
下一步,實現用重力感應來操控